- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Why do we need inner classes in Java?
Inner classes are a security mechanism in Java. We know a class cannot be associated with the access modifier private, but if we have the class as a member of other class, then the inner class can be made private. And this is also used to access the private members of a class.
Following is the program to create an inner class and access it. In the given example, we make the inner class private and access the class through a method.
Example
class Outer_Demo { int num; // inner class private class Inner_Demo { public void print() { System.out.println("This is an inner class"); } } //Accessing he inner class from the method within void display_Inner() { Inner_Demo inner = new Inner_Demo(); inner.print(); } } public class My_class { public static void main(String args[]) { //Instantiating the outer class Outer_Demo outer = new Outer_Demo(); //Accessing the display_Inner() method. outer.display_Inner(); } }
Output
This is an inner class.
- Related Articles
- Why do we need generics in Java?
- Why do we need a wrapper class in Java?
- Why do we need KDD?
- Why do we need Energy?
- Why do we need weakMaps in Javascript?
- Why do we need Good Manners?
- Why do we need a Database
- Why do we need Computer Networks?
- Why do we need shell scripting?
- Why do we need Data Encryption?
- Why do we need private methods in an interface in Java 9?
- Why do we need to study Physics?
- Why do we need to store food?
- What are inner classes in Java?
- Do we need forward declarations in Java?

Advertisements