Tuesday, April 12, 2011

JAVA Programming : Abstract Class and Abstract Method

JAVA Abstract Classes and Abstract Methods 


Abstract Class: An abstract class is declared using abstract keyword. An abstract class is a class definition that is incomplete in the sense that it has some abstract methods. It is not compulsory that an abstract class has an abstract method but if a class has an abstract method, the class has to be declared as abstract. Abstract classes can never be initiated but they can be subclassed.

Abstract Method: Abstract method are declared using abstract keyword. Abstract methods are defined as part of the class but the inner workings (body of methods) are not provided. Abstract methods ends with semicolon instead of curly brackets. 


   public abstract class Bike {       
       abstract void gear();
       abstract void topSpeed();

   }


Why we need an Abstract Class: This is the question that many people ask about, what is the need of abstract class. The idea behind an abstract class is putting common functionality to an abstract class that other classes will extend.
For example we can have a abstract class named fan with a method for turning the fan on and off but not defining the procedure to do that i.e. with no body declaration. Now we can extend the fan class into table fan and define on and off procedure accordingly or we can extend the fan class to ceiling fan and define on and off procedure according to ceiling fan.

No comments:

Post a Comment