Samuel Fernandes

Total Post:38

Posted by  Samuel Fernandes
 761  View(s)
Rate this:
  1. Mayank Tripathi


    What is abstract class?

    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

      Modified On Mar-28-2018 12:10:33 AM



Enter your email address here always to be updated. We promise not to spam!