[Tutorial] Java Abstract Class


Submit solution

Points: 10
Time limit: 1.0s
Memory limit: 2M

Author:
Problem type
Allowed languages
Java

Abstract Class and Method

Abstract Class is a restricted class that cannot be used to create objects. The abstract class can only be inherited to another class to access it.

Abstract method can only be declared in an abstract class which does not have any definition. The definition is provided by the subclass which inherited the abstract class.

Example

/*
* Created: Ramaguru Radhakrishnan
* Date: 08-May-2023
*
*/
abstract class Shape {

  // Abstract Method without Definition
  public abstract void area();

  // Method
  public void display() {
    System.out.println("[Super] Calculating Area");
  }

}

// Subclass (inherited from Shape)
class Circle extends Shape {

  public void area() {
     // area() of Circle Class - Definition
    System.out.println("[Abstract Method in Circle] Area of Circle is PI*R*R");
  }

}

// Subclass (inherited from Shape)
class Rectangle extends Shape {

  public void area() {
    // area() of Rectangle Class - Definition
    System.out.println("[Abstract Method in Rectangle] Area of Rectangle is L*B");
  }

}

public class Main {

  public static void main(String[] args) {

    System.out.println("[Main] Creating Object for Abstract Class is not possible");  

    // Shape myShape = new Shape(); //Try uncommenting this line.

    //error: Shape is abstract; cannot be instantiated

    System.out.println("[Main] Creating Objects Circle and Rectangle");  
    Circle myCircle = new Circle(); // Create a Circle object
    myCircle.display();
    myCircle.area();

    Rectangle myRect = new Rectangle(); // Create a Rectangle Object
    myRect.display();
    myRect.area();
  }

}

Comments

There are no comments at the moment.