Saturday, 7 March 2015

ABSTRACT CLASS IN JAVA

Abstract class in Java

A class that is declared with abstract keyword, is known as abstract class in java. It can have abstract and non-abstract methods (method with body).
Before learning java abstract class, let's understand the abstraction in java first.

Abstraction in Java

Abstraction is a process of hiding the implementation details and showing only functionality to the user.
Another way, it shows only important things to the user and hides the internal details for example sending sms, you just type the text and send the message. You don't know the internal processing about the message delivery.
Abstraction lets you focus on what the object does instead of how it does it.

Abstract class in Java

A class that is declared as abstract is known as abstract class. It needs to be extended and its method implemented. It cannot be instantiated.

Example abstract class

abstract class A{}

abstract method
A method that is declared as abstract and does not have implementation is known as abstract method.

Example abstract method

  1. abstract void printStatus();//no body and abstract  

Example of abstract class that has abstract method

In this example, Bike the abstract class that contains only one abstract method run. It implementation is provided by the Honda class.
  1. abstract class Bike{  
  2.   abstract void run();  
  3. }  
  4.   class Honda4 extends Bike{  
  5. void run(){
  6. System.out.println("running safely..");
  7. }  
  8.   public static void main(String args[]){  
  9.  Bike obj = new Honda4();  
  10.  obj.run();  
  11. }  
  12. }  
running safely..

Another example of abstract class in java

  1.  abstract class Bank{    
  2. abstract int getRateOfInterest();    
  3. }    
  4.     
  5. class SBI extends Bank{    
  6. int getRateOfInterest(){return 7;}    
  7. }    
  8. class PNB extends Bank{    
  9. int getRateOfInterest(){return 7;}    
  10. }    
  11.     
  12. class TestBank{    
  13. public static void main(String args[]){    
  14. Bank b=new SBI();//if object is PNB, method of PNB will be invoked    
  15. int interest=b.getRateOfInterest();    
  16. System.out.println("Rate of Interest is: "+interest+" %");    
  17. }}  
Rate of Interest is: 7 %


No comments:

Post a Comment