aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes doubt in static method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "doubt in static method" Watch "doubt in static method" New topic
Author

doubt in static method

Nik Arora
Ranch Hand

Joined: Apr 26, 2007
Posts: 652
class A
{
}
public class TestClass
{
public class A
{
public void m() { }
}
class B extends A
{
}
public static void main(String args[])
{
new TestClass().new A() { public void m() { } };
}
}


Can anyone explain me how this works?
Chandra Bhatt
Ranch Hand

Joined: Feb 28, 2007
Posts: 1707
Well indented code inside the code tag looks good,



Here you go:
TestClass is top level class. Inside that there is a class A call inner class. And one more class is there called class B that extends class A of the TestClass.

Inside the main method of TestClass, there is anonymous class implementation. Anonymous class means no name of the class, but it extends
or implements (in both case extends keyword is used) a class or interface accordingly. But it can only do either of one.

Inside that anonymous class, you have overridden the method m of class A.

Important point: You can't instantiate the inner class without having reference of the outer class in which the inner is enclosed. Non static methods do have "this" so they can create inner class object like:

A a1 = new A();

Because there is no this reference in the static method (in your case main()), we must create instance of the TestClass before instantiating the class A as we did:

new TestClass().new A() {
...
}; //must end with semicolon



Regards,
cmbhatt
[ April 28, 2007: Message edited by: Chandra Bhatt ]

cmbhatt
Nik Arora
Ranch Hand

Joined: Apr 26, 2007
Posts: 652
I got this thanks chandra
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: doubt in static method
 
Similar Threads
Inner Class
can we have public inner class
2 public classes in one file??
static inner class
Inner Class