• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Nested Classes

 
Supun Lakshan Dissanayake
Ranch Hand
Posts: 135
Android Java PHP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!!!
 
Campbell Ritchie
Sheriff
Pie
Posts: 49466
64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please supply fuller details. What did the compiler error say? Was it anything about this is a static context?
 
harshvardhan ojha
Ranch Hand
Posts: 157
1
Android Java MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 135
Android Java PHP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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();

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic