February 1, 2011

Effect of abstract keyword on classes and methods

A class marked with the abstract keyword cannot be instantiated. It has to be subclassed to be useful.

public abstract class Test {
   public static void main(String[] args) {
      Test t = new Test();       // will not compile    
   }
}

A method marked as abstract cannot have a body (is not implemented) and ends with a semi-colon.

public abstract class Test {
   public abstract void m1();
}

Abstract classes may have abstract methods.
But an abstract method must be present in an abstract class.
Non-abstract (Concrete) classes cannot have abstract methods.

public class Test {
   public abstract void m1(); // will not compile
}

public abstract class Test {
   public abstract void m2() {  // will not compile

   }
}

No comments:

Post a Comment