Monday, December 12, 2011

Class Definition » Abstract Class

Abstract Classes
  1. Provide a contract between a service provider and its clients.
  2. An abstract class can provide implementation.
  3. To make an abstract method, use the abstract modifier in front of the method declaration.
public abstract class DefaultPrinter {
  public String toString() {
    return "Use this to print documents.";
  }

  public abstract void print(Object document);
}
  1. The toString method has an implementation, so you do not need to override this method.
  2. The print method is declared abstract and does not have a body.
public class MyPrinter extends DefaultPrinter {
  public void print(Object document) {
    System.out.println("Printing document");
    // some code here
  }
}
 
A demonstration of abstract.
abstract class {
  abstract void callme();

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

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

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

    b.callme();
    b.callmetoo();
  }
}
 
Using abstract methods and classes.
abstract class Figure {
  double dim1;

  double dim2;

  Figure(double a, double b) {
    dim1 = a;
    dim2 = b;
  }

  abstract double area();
}

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

  double area() {
    System.out.println("Inside Area for Rectangle.");
    return dim1 * dim2;
  }
}

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

  double area() {
    System.out.println("Inside Area for Triangle.");
    return dim1 * dim2 / 2;
  }
}

class AbstractAreas {
  public static void main(String args[]) {
    Rectangle r = new Rectangle(95);
    Triangle t = new Triangle(108);
    Figure figref;

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

    figref = t;
    System.out.println("Area is " + figref.area());
  }
}
 
 
http://www.java2s.com/Tutorial/Java/0100
__Class-Definition/Catalog0100__Class-Definition.htm

No comments:

Post a Comment