permaculture playing cards*
The moose likes Beginning Java and the fly likes Nested Classes Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Nested Classes" Watch "Nested Classes" New topic
Author

Nested Classes

Supun Lakshan Dissanayake
Ranch Hand

Joined: Oct 26, 2012
Posts: 132

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!!!


Are you better than me? Then please show me my mistakes..
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37907
    
  22
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: 157
    
    1

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: 132

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();

 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Nested Classes
 
Similar Threads
answers to java.ditmas.net Mock Exam
top level nested class
Nested Classes
FYI - Subclassing from an Inner Class
Outside code as an Inner class