What are Abstract Classes

You can require that certain methods be overridden by subclasses by specifying the abstract type modifier. To declare an abstract method, use this general form:


abstract type name(parameter-list);

No method body is present for abstract method.

Any class that contains one or more abstract methods must also be declared abstract.


abstract class MyAbstractClass{
   abstract type name(parameter-list); 
}

Here is an abstract class, followed by a class which implements its abstract method.

 
abstract class MyAbstractClass {
  abstract void callme();

  void callmetoo() {
    System.out.println("This is a concrete method.");
  }
}

class B extends MyAbstractClass {
  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 output:


B's implementation of callme.
This is a concrete method.

Using abstract methods and classes

 
abstract class Shape {
  double height;
  double width;

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

class Rectangle extends Shape{
  Rectangle(double a, double b) {
    super(a, b);
  }
  double area() {
    System.out.println("Inside Area for Rectangle.");
    return height * width;
  }
}
class Triangle extends Shape{
  Triangle(double a, double b) {
    super(a, b);
  }
  double area() {
    System.out.println("Inside Area for Triangle.");
    return height * width / 2;

  }
}

public class Main {
  public static void main(String args[]) {
    Rectangle r = new Rectangle(10, 5);
    Triangle t = new Triangle(10, 8);

    Shape figref;

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

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

The output:


Inside Area for Rectangle.
Area is 50.0
Inside Area for Triangle.
Area is 40.0
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.