Java Abstract Class Create

Introduction

Abstract class is for abstract idea.

Here is a simple example of a class with an abstract method, followed by a class which implements that method:

// A Simple demonstration of abstract.
abstract class A {
  abstract void callme();

  // concrete methods are still allowed in abstract classes
  void callmetoo() {
    System.out.println("This is a concrete method.");
  }/*from  w w  w . ja  v a2  s. c  om*/
}

class B extends A {
  void callme() {
    System.out.println("B's implementation of callme.");
  }
}

public class Main {
  public static void main(String args[]) {
    B b = new B();

    b.callme();
    b.callmetoo();
  }
}

The following code shows how to use abstract class to define an abstract concept.

The Shape is an abstract concept. Its subclass provides a concrete implementation.


// Using abstract methods and classes.
abstract class Shape {
  double width;//from ww w .ja  va2s . c  o  m
  double height; 

  Shape(double a, double b) {
    width = a;
    height = b;
  }

  // area is now an an abstract method 
  abstract double area();
}

class Rectangle extends Shape {
  Rectangle(double a, double b) {
    super(a, b);
  }

  // override area for rectangle
  double area() {
    System.out.println("Inside Area for Rectangle.");
    return width * height;
  }
}

class Triangle extends Shape {
  Triangle(double a, double b) {
    super(a, b);
  }

  // override area for right triangle
  double area() {
    System.out.println("Inside Area for Triangle.");
    return width * height / 2;
  }
}

public class Main {
  public static void main(String args[]) {
    Rectangle r = new Rectangle(9, 5);
    Triangle t = new Triangle(10, 8);
    
    Shape figref; // this is OK, no object is created

    figref = r;
    System.out.println("Area is " + figref.area());
    
    figref = t;
    System.out.println("Area is " + figref.area());
  }
}



PreviousNext

Related