Website For Developers

Abstract Class in Java



Syntax

abstract class className {
  //Abstract Method
  abstract return_type method_name(Parameters);
  ........
  ........
}


Example of Abstract Class in Java

abstract class A {

  //abstract method without body
  abstract void output();
}

class B extends A {

  //abstract method implementation
  void output() {
    System.out.println( "Welcome to OnlineProgrammingHub!" );
  }
}

public class App {

  public static void main(String[] args) {
    B obj = new B();
    obj.output();
  }
}

Output


Abstract Class in Java Example

import java.util.Scanner;

abstract class Shape {
  abstract double area();
}

class Rectangle extends Shape {
  double width, height;
  public double area() {
    return width * height;
  }
}

class Triangle extends Shape {
  double base, height;
  public double area() {
    return 0.5 * base * height;
  }
}

class App {
   public static void main(String[] args) {
     Scanner scan = new Scanner(System.in);
     Shape ref; //Polymorphism

     Rectangle rec = new Rectangle();
     System.out.print( "Enter Width: " );
     rec.width = scan.nextDouble();
     System.out.print( "Enter Height: " );
     rec.height = scan.nextDouble();
     ref = rec;
     System.out.println( "Area of Rectangle = " + ref.area());

     Triangle tri = new Triangle();
     System.out.print( "Enter base of triangle: " );
     tri.base = scan.nextDouble();
     System.out.print( "Enter width of triangle: " );
     tri.height = scan.nextDouble();
     ref = tri;
     System.out.println( "Area of Triangle = " + ref.area());
   }
}

Output

Enter Width: 3
Enter Height: 4
Area of Rectangle = 12.0
Enter base of triangle: 12
Enter width of triangle: 6
Area of Triangle = 36.0