articles

Home / DeveloperSection / Articles / Abstract Class in Java

Abstract Class in Java

Anupam Mishra4572 11-Dec-2015

If you are declared with abstract keyword of a class is called abstract class. It can

have abstract and non-abstract method (method with body).

It need to be extended and its method implemented to another class.it can’t be instantiated.

abstract class Abc{}

abstract method :

A method i.e. declared abstract & does not have implementation is known as abstract method within a Abstract class.

abstract void getMilkPrice ();


Note:

1. If any class are declared any abstract method then that class must be abstract

2. If you are extending any abstract class that have abstract method then you must either provide the implementation of the method or make this class abstract. 

Real Scenario of abstract class:

For take example, Milk is the abstract class,its implementation is provided by the Amul,Prag and NamsteIndia classes. Mostly, we don’t know about the implementation class (i.e. hidden to the end user) and object of the implementation class is provided by the factory method.A factory method is the method that returns the instance of the class

In this example, if you create the instance of Amul class, getMilkPrice() method of Amul class will be invoked.Similarily,other two classes does.

abstract class Milk{    
abstract int getMilkPrice();    
}    
    
class Amul extends Milk{    
int getMilkPrice(){return 20;}    
}    
class Prag extends Milk{    
int getMilkPrice(){return 19;}    
}    
class NamsteIndia extends Milk{    
int getMilkPrice(){return 18;}    
}    
    
class MilkPriceTest{    
public static void main(String args[]){    
Amul b=new Amul();//if object is Amul
int Price=b. getMilkPrice();    
System.out.println("Price of Amul Milk is : "+Price+" Rs"); 
Prag b1=new Prag();//if object is Prag
 Price=b1. getMilkPrice();    
System.out.println("Price of Prag Milk is : "+ Price +" Rs"); 
NamsteIndia b2=new NamsteIndia();//if object is Namste India
int Price=b1. getMilkPrice();    
System.out.println("Price of NamsteIndia Milk is : "+Price+" Rs");    
}}    

 


Updated 14-Dec-2017

Leave Comment

Comments

Liked By