| Author |
Nested Classes
|
Supun Lakshan Dissanayake
Ranch Hand
Joined: Oct 26, 2012
Posts: 46
|
|
I tried to create an object of D by creating an object of Outer class and using it's reference to create an object of D.
Here is the code I tried.
I know Outer.D a = new Outer.D(); is OK and I don't need an explanation for it.
All I want to know why we can't create an object of D when we use reference variable of Outer object
Regards!!!
|
Try and Try one day you can FLY.
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32611
|
|
|
Please supply fuller details. What did the compiler error say? Was it anything about this is a static context?
|
 |
harshvardhan ojha
Ranch Hand
Joined: Jul 26, 2007
Posts: 155
|
|
Hi Supun, it just looks like your inner class D is inside Outer class, but it is actually not.
Static classes are as good as an outer classes, this can only behave as class level member but not instance level member.
|
 |
Supun Lakshan Dissanayake
Ranch Hand
Joined: Oct 26, 2012
Posts: 46
|
|
Oh sorry.
My mistake.
Inner should be D
and
Outer.D c = a.new D(); //compile time error
should be
Outer.D c = b.new D(); //compile time error
now the question is appear as it should.
Campbell Ritchie wrote:What did the compiler error say? Was it anything about this is a static context?
Here is the compile time error
C:\Java\Demo.java:14: error: qualified new of static class
Outer.D c = b.new D(); //compile time error
^
1 error
|
 |
vinay chaturvedi
Greenhorn
Joined: Jan 16, 2012
Posts: 14
|
|
A static nested class behaves as any other top-level class. A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class.
Static nested classes are accessed using the enclosing outer class name:
"Outer.D"
For example, to create an object for the static nested class, use this syntax :
Outer.D nestedObject = new Outer.D();
For non-static nested classes you can create object as :
Outer.D nestedObject = new Outer().new D();
OR,
Outer outer = new Outer();
Outer.D nestedObject = outer.new D();
|
 |
 |
|
|
subject: Nested Classes
|
|
|