Friday 19 April 2013

Abstract classes and functions in java

Abstract classes are the basis for what is yet to come - interfaces. So lets understand what are abstract classes and why are these important.

In the tutorial on polymorphism we saw how reference of type Animal can be used to point at object of various types like Cat,Dog,Lion,Wolf,Hippo etc. 
 
Just to revise things we now know we can say -

Wolf aWolf = new Wolf();


or we can also say -

Animal aHippo = new Hippo (); 


 but what happens when we do -

Animal animal = new Animal();

Perfectly Valid Java syntax. But what does this Animal look like?

This only makes sense when we have some concrete Animal like Dog,Cat etc . In short it does not make any sense to create objects of class Animal or in other words it does not  make any sense to use new() operator with Animal class. In this case we declare the class as abstract. Such abstract classes are used in polymorphism.

Syntax for making abstract classes
abstract public class Animal

Note: Though we cannot create objects of abstract classes we can use them as reference (like in Polymorphism).

Also remember you cannot use functions of subclass through super class reference(polymorphism) unless the function is defined in the super class. But also we cannot implement the function in the super class as the implementation will be subclass specific( eg different implementation for Dog,Cat etc). To sum thing up, for using polymorphism effectively we need function declared in super class and it's concrete implementation in the subclass. Hence we define the functions to be abstract.

Syntax for abstract function -
abstract returnType functionName(Arguments);

Note : No Method body. No brace brackets. Just a semicolon after method declaration. 


 Observe the semi colon after function prototype.  We just declare it and put a semi colon after it. Implementation of this function will be in the first concrete class which implements this abstract class. There is no use of abstract class if no class implement it(i.e if there are no subclasses of abstract class).

Note: There can be non-abstract functions in abstract classes but there can never be abstract functions in a non-abstract class. So if you have abstract functions you must declare your class to be abstract.

Also note there is no such thing as abstract variables. In java we just have abstract classes and abstract function.

Few points to note

  1. A non abstract class cannot have abstract method. If a class has abstract method it has to be made abstract.
  2. We cannot instantiate abstract classes.
  3. An abstract class can have non abstract methods .
  4. If your abstract class has all abstract method it is better to go for an interface instead.









t> UA-39527780-1 back to top