Monday, February 11, 2013

Can we override the main method() ?


Technically the answer is NO. 

> Main method is a static method.
> Static methods belong to the class and not to the objects.
> If you extend a Parent class having main method the child class doesn't have the parent class's main method so there is no question about overriding it.
> You can write your own main method in the child class but that would be again a static method of the child class and would have nothing to do with the main method of the parent class.

Following code will compile and will execute fine...

public class Parent{
    public static void main(String args[]){
        System.out.println("In Parents main method..");
}
class child extends Parent{
  public static void main(String args[]){
        System.out.println("In childs main method..");
}
You can even call the main method of other class from one class directly as its a static method!!

Any questions??

No comments: