| Author |
why this abstract class containing a main method getting executed?
|
Anil Deshpande
Ranch Hand
Joined: Jan 13, 2008
Posts: 117
|
|
This is really weird for me.
The following code gets executed.
and Actually prints
But if I modify the code it works as expected as you can not create an instance of an abstract class.
It (compiler) says compilation error.
But once again if I change the class and give the implementation of the default constructor
It compiles fine and executes fine.
But once again I can not instantiate the object of that AbstractClass even though I have implemented default constructor.
i.e.
So Whats actually happening?
Is it still working as per the Java convention?
Please some body explain.
Regards,
Anil Deshpande
|
Anil Deshpande
SCJP 1.5, SCWCD 1.5
|
 |
Matthew Brown
Bartender
Joined: Apr 06, 2010
Posts: 3795
|
|
Abstract just means you can't instantiate the class directly. You can have constructors if you want - they might be needed for subclasses to initiate the object state. You can have static methods (including main()) - and they don't need an object so calling them is fine.
So you only got errors when you tried to create the object, which is when you run into the abstract limitation.
What did you expect to happen differently?
|
 |
Anil Deshpande
Ranch Hand
Joined: Jan 13, 2008
Posts: 117
|
|
I had thought that one can not run even a main method inside an abstract class.
Because even java interpreter need to load the class before running main. For that it need to have a constructor and if it loads a class which is abstract it can not instantiate the object and thus can not run main inside it.
Correct me if If I am wrong.
|
 |
Matthew Brown
Bartender
Joined: Apr 06, 2010
Posts: 3795
|
|
|
Loading a class is not the same as creating an instance of the class. And there's no need to create an instance of the class to call main(), because it's static. So there's no problem, and the lack or otherwise of a constructor is irrelevant.
|
 |
Shanky Sohar
Ranch Hand
Joined: Mar 17, 2010
Posts: 1046
|
|
Remember these point for classes..
1. every class(including Abstract class) is having a default no-args constructor(until and unless,you yourself give the args constructor) given by the compiler which is having the same visibility as of class..
2.And one more thing you can even have a abstract class that has no abstract methods.
3.You cannot instantiate a abstract class.
|
SCJP6.0,My blog Ranchers from Delhi
|
 |
 |
|
|
subject: why this abstract class containing a main method getting executed?
|
|
|