aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) 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 Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Nested classes" Watch "Nested classes" New topic
Author

Nested classes

Duran Harris
Ranch Hand

Joined: Nov 09, 2008
Posts: 598

Can nested classes have constructors??


===>SCJP 1.5(72%)<===
==>SCWCD1.5(76%)<===
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9280
    
  17

All nested classes except anonymous inner classes can have constructors...


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Duran Harris
Ranch Hand

Joined: Nov 09, 2008
Posts: 598

Ok...

no special rules apply?
Ruben Soto
Ranch Hand

Joined: Dec 16, 2008
Posts: 1032
Ankit is right. If you want to be overly technical, you could say that all classes can (and indeed must) have constructors. When you don't explicitly declare a constructor, the class obtains the default constructor provided by the compiler. In the case of an anonymous inner class, it is clear why you can't have an explicitly defined constructor, because the constructor must have the same name as the class, but...what's the name of an anonymous class? However, the anonymous inner class must get a default constructor that simply calls the super() constructor of the class extended by the anonymous class (if the anonymous class extends a class.) If the anonymous class instead implements an interface, and given that interfaces do not have constructors, the anonymous class will get a default constructor that doesn't do anything.


All code in my posts, unless a source is explicitly mentioned, is my own.
Duran Harris
Ranch Hand

Joined: Nov 09, 2008
Posts: 598

I'm having a problem with instantiating an innner class from a static context...Could you tell me where I'm going wrong??

Punit Singh
Ranch Hand

Joined: Oct 16, 2008
Posts: 952


Inner4 is method local class, so just instantiate is as line1.


SCJP 6
Ruben Soto
Ranch Hand

Joined: Dec 16, 2008
Posts: 1032
Inner4 looks like a method-local inner class. You need to instantiate it the same way that you are instantiating Inner3. The only difference is that since Inner4 is inside a static method, Inner4 won't be able to access any instance members from the enclosing class, just static members.

Edit: What Punit said. He must have submitted his reply while I was writing mine.
Duran Harris
Ranch Hand

Joined: Nov 09, 2008
Posts: 598

Ah good...

I can see the pattern in syntax for instantiating inner classes now
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Nested classes
 
Similar Threads
Access specifiers
Member class vs inner class
inner class
answer please
inner classes