ContactUs :

Please send your Questions & Answers or Feedback to "mohan@javabook.org"

What is abstract class in Java ?

An abstract class is something which is incomplete and you can not create instance of abstract class. If you want to use it you need to make it complete or concrete by extending it. A class is called concrete if it does not contain any abstract method and implements all abstract method inherited from abstract class or interface it has implemented or extended.

 

Popular example of abstract class in Java is ActionListener which has abstract method called actionPerformed(ActionEvent ae). This method is called when an ActionEvent is fired like when you click on JButton. Its common in java to attach ActionListener with JButton by implementing abstract method actionPerformed(ActionEvent ae) using Anonymous class, as shown in below Example :

JButton  ok = new JButton("OK");

ok.addActionListener(new ActionListener(){

           public void  actionPerformed(ActionEvent ae){

               //code to handle event

           }

});

In order to use abstract method you need to override that method in SubClass.

 

Java Interface is an another way of providing abstraction, Interfaces are by default abstract and only contains public static, final constant or abstract methods

 

Interface like Runnable are good example of abstraction in Java which is used to abstract task executed by multiple thread.

 

1) Use abstraction if you know something needs to be in class but implementation of that varies.

2) In Java you can not create instance of abstract class , its compiler error.

3) abstract is a keyword in java.

4) a class automatically becomes abstract class when any of its method declared as abstract.

5) abstract method doesn't have method body.

6) variable can not be made abstract , its only behavior or methods which would be abstract.

7) If a class extends an abstract class or interface it has to provide implementation to all its abstract method to be a concrete class. alternatively this class can also be abstract.

Related Posts Plugin for WordPress, Blogger...
Flag Counter