Inner classes in java
In
java inner class which is defined inside another class is called nested class
or non-static inner class. For instantiating the inner class or nested class object we first need to
create the outer class object. We can access outer class member’s
variables insides of inner class just like normal members variables of class.
We cannot
declare static method or static variable inside the non-static inner class. If we
try to declare it shows error The field or static variable cannot be declared static in a non-static
inner type.
Below
is syntax of the inner class.
public class OuterClass
{
// inner class or non-static nested class
class InnerClass
{
//..
}
}
A benefit of nested class is we can make our code more encapsulated so lets check below
is an example of how you can declare inner classes in Java.
public class OuterClass
{
String country = "India";
static String language = "java";
class InnerClass
{
public void display(){
System.out.println(language);
System.out.println(country);
}
}
public static void main(String[] args) {
// create object of Outer class
OuterClass outerCls = new OuterClass();
// create an object of inner class using outer class object refrance
OuterClass.InnerClass innerCls = outerCls.new InnerClass();
innerCls.display();
}
}
Output
java
India
Inner class present in the outer class, so we must instantiate the outer class first, in order to instantiate the inner class.
Else you
can write the method in outer class which can create the object of inner class
and call that method, Check below example for more details.
public class OuterClass
{
String country = "India";
static String language = "java";
class InnerClass{
public void display(){
System.out.println(language);
System.out.println(country);
}
}
public void initiateClass(){
InnerClass innerCls = new InnerClass();
innerCls.display();
}
public static void main(String[] args) {
OuterClass outerCls = new OuterClass();
outerCls.initiateClass();
}
}
Output
java
India
If the
outer class member variable is re-declared in the inner class then for accessing
the member variable of outer class we need to use this
keyword with outer class name like OuterClass.this.variableName.
Important Note: Inner
classes are members of the outer class, so you can apply any access modifiers like private, protected to your inner class which is not
possible in normal outer classes.
I
hope you enjoyed by reading this article if any suggestion please write down
below in comment section.
0 comments:
Post a Comment