Home > DeveloperSection > Interviews > What is abstract class?

Posted on    April-03-2015 12:13 AM

 Java Java 
 1 Answer(s)
  601  View(s)
Rate this:

Mayank Tripathi
Mayank Tripathi

Total Post:807

Posted on    April-03-2015 12:49 AM

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).
It needs to be extended and its method implemented. It cannot be instantiated.
    abstract class A{}  
Abstract method: A method that is declared as abstract and does not have implementation is known as abstract method.
  abstract void printStatus();//no body and abstract  
Example:Bike the abstract class that contains only one abstract method run. It implementation is provided by the Honda class.
abstract class Bike{  
  abstract void run();  
class Honda4 extends Bike{  
void run(){System.out.println("running safely..");}  
public static void main(String args[]){  
 Bike obj = new Honda4();  

Output : running safely..

Real Scenario
Shape is the abstract class, its implementation is provided by the Rectangle and Circle 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. We will learn about the factory method later.
In this example, if you create the instance of Rectangle class, draw() method of Rectangle class will be invoked
abstract class Shape{  
abstract void draw();  
//In real scenario, implementation is provided by others i.e. unknown by end user  
class Rectangle extends Shape{  
void draw(){System.out.println("drawing rectangle");}  
class Circle1 extends Shape{  
void draw(){System.out.println("drawing circle");}  
//In real scenario, method is called by programmer or user  
class TestAbstraction1{  
public static void main(String args[]){  
Shape s=new Circle1();//In real scenario, object is provided through method e.g. getShape() method  
Output: drawing circle

Don't want to miss updates? Please click the below button!

Follow MindStick