| Author |
Is it possible to override main method?
|
Athira Vineeth
Greenhorn
Joined: Sep 06, 2010
Posts: 16
|
|
Hi
Is it possible to override main method?
Thanks in Advance
Athira
|
 |
Matthew Brown
Bartender
Joined: Apr 06, 2010
Posts: 3791
|
|
|
Assuming you mean the main method (and not just any old method called main) - main is a static method, and you can't override static methods. So no.
|
 |
Athira Vineeth
Greenhorn
Joined: Sep 06, 2010
Posts: 16
|
|
Thanks for the reply.
But still i am in confusion
i have a class called MainClass
one subclass called that xtend main class
here the signature of main method is same that means main method got overriden .right?
|
 |
Matthew Brown
Bartender
Joined: Apr 06, 2010
Posts: 3791
|
|
No. What you've got there is method hiding, not overriding.
The difference is, if you call MyMainClass.main, you'll get the version in MyMainClass. If you call OverridingMain.main, you'll get the version in OverridingMain - there are two separate methods, and you don't get any polymorphic behaviour.
It's called hiding because if you just call main in OverridingMain it will call that version, whereas if you deleted that main method it would call the one in MyMainClass - the existence of the method in the subclass has "hidden" the one in the superclass, which then has to be accessed via the class name.
|
 |
Sumit Patil
Ranch Hand
Joined: May 25, 2009
Posts: 296
|
|
Hello,
In Java we can not override a method which is static, but we can implement the method with the same name and parameters. This is called shadowing and not overriding.
Hope this helps.
|
Thanks & Regards, Sumeet
SCJP 1.4, SCWCD 5, LinkedIn Profile
|
 |
Athira Vineeth
Greenhorn
Joined: Sep 06, 2010
Posts: 16
|
|
In a class hierachy, when a method in a subclass has the same name and type signature as a method in its super class, then a method in the subclass is said to override the method in the super class.
When an overriden method is called from within a subclass, it will always refer to the version of that method defined by the subclass.The version of the method defined by the superclass will be hidden.
In that sense main method is said to be overriding.right?
|
 |
Matthew Brown
Bartender
Joined: Apr 06, 2010
Posts: 3791
|
|
Athira Vineeth wrote:In that sense main method is said to be overriding.right?
No. As I said, overriding does not apply to static methods.
See this section of the Java Language Specification if you want the definitive answer (though it's not always easy to read). Section 8.4.8.1. about overriding refers to instance methods, and section 8.4.8.2. about hiding refers to static methods.
|
 |
Athira Vineeth
Greenhorn
Joined: Sep 06, 2010
Posts: 16
|
|
Thanks Brown!!
that link is very helpful.
it is clear now
From this example
output is Goodnight, Dick
Thanks
Athira
|
 |
 |
|
|
subject: Is it possible to override main method?
|
|
|