Thursday 27 August 2015

Can we declare main() method in abstract class?

YES, We can declare the main() method in abstract class.

abstract class Test {

       public static void main(String args[] ) {
              System.out.println("Abstract class : main method");

       }
       abstract void remove();
}
Output:
Abstract class : main method


abstract class Test {
       public Test() { // to invoke by child class
    }
      
       public static void main(String args[] ) {
              System.out.println("Abstract class : main method");
              new Test();   // Cannot instantiate the type Test

       }
       abstract void remove();
}

Why this abstract class containing a main method getting executed?

Abstract just means you can't instantiate the class directly.

It can have constructors- it might be needed for subclasses to initiate the object state.

It can have static methods (including main ()) – It doesn'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.

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. One more thing you can even have an abstract class that has no abstract methods.

3. Cannot instantiate an abstract class.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...