Now, make everything non static in above program (TempNonStatic.java):
package com.dev21century;
class NonStaticOuter {
int x = 10;
static int y = 20;
class Inner
{
void show()
{
System.out.println("x = " + x);
System.out.println("y from show = " + y);
}
}
}
public class TempNonStatic {
public static void main(String args[])
{
NonStaticOuter outer = new NonStaticOuter();
System.out.println("outer.x = " + outer.x);
NonStaticOuter.Inner inner = outer.new Inner();
inner.show();
}
}
In above program, as we know inner class is a non static class, so we must have to create an object before accessing its properties. So, the syntax to create such object is:
NonStaticOuter.Inner inner = outer.new Inner()
Rule- a non static nested class can access all data members and methods of its outer class.
Inner class is not extending outer and not creating any object of it then how inner is able to access x variable of outer class?
Because there are two ways for accessing non static data member of other class.
Data Shadowing in Inner class:
Let’s assume that there is a local variable x inside Inner class in above program, then priority always goes to the local variable. So, let’s discuss how we can access the data member of outer class. The way is: “Outer.this.x”
Here is the full-fledged program (TempNonStatic.java):
package com.dev21century;
class NonStaticOuter {
int x = 10;
static int y = 20;
class Inner
{
int x = 30;
void show()
{
System.out.println("local inner x = " + x);
System.out.println("outer x = " + NonStaticOuter.this.x);
System.out.println("y from show = " + y);
}
}
}
public class TempNonStatic {
public static void main(String args[])
{
NonStaticOuter outer = new NonStaticOuter();
System.out.println("outer.x = " + outer.x);
NonStaticOuter.Inner inner = outer.new Inner();
inner.show();
}
}
Rule – non static nested class cannot have its personal static data members or static methods. Which means the main() method cannot be added in non static inner class hence a non static inner class cannot be made as self executable.
Inheritance of non static class – we can extend the outer class but its inner class cannot be inherited in sub class.
No comments:
Post a Comment