Java Tutorial/Class Definition/Polymorphism

Материал из Java эксперт
Перейти к: навигация, поиск

An example of polymorphism

class Employee {
  public void work() {
    System.out.println("I am an employee.");
  }
}
class Manager extends Employee {
  public void work() {
    System.out.println("I am a manager.");
  }
  public void manage() {
    System.out.println("Managing ...");
  }
}
public class PolymorphismTest1 {
  public static void main(String[] args) {
    Employee employee;
    employee = new Manager();
    System.out.println(employee.getClass().getName());
    employee.work();
    Manager manager = (Manager) employee;
    manager.manage();
  }
}





Constructors and polymorphism don"t produce what you might expect

abstract class Glyph {
  abstract void draw();
  Glyph() {
    System.out.println("Glyph() before draw()");
    draw();
    System.out.println("Glyph() after draw()");
  }
}
class RoundGlyph extends Glyph {
  private int radius = 1;
  RoundGlyph(int r) {
    radius = r;
    System.out.println("RoundGlyph.RoundGlyph(), radius = " + radius);
  }
  void draw() {
    System.out.println("RoundGlyph.draw(), radius = " + radius);
  }
}
public class MainClass {
  public static void main(String[] args) {
    new RoundGlyph(5);
  }
}



Glyph() before draw()
RoundGlyph.draw(), radius = 0
Glyph() after draw()
RoundGlyph.RoundGlyph(), radius = 5


Downcasting and Run-Time Type Identification (RTTI)

class Useful {
  public void f() {
  }
  public void g() {
  }
}
class MoreUseful extends Useful {
  public void f() {
  }
  public void g() {
  }
  public void u() {
  }
  public void v() {
  }
  public void w() {
  }
}
public class MainClass {
  public static void main(String[] args) {
    Useful[] x = { new Useful(), new MoreUseful() };
    x[0].f();
    x[1].g();
    // x[1].u();
    ((MoreUseful) x[1]).u(); // Downcast/RTTI
    ((MoreUseful) x[0]).u(); // Exception thrown
  }
}





Dynamic Method Dispatch

class A {
  void callme() {
    System.out.println("Inside A"s callme method");
  }
}
class B extends A {
  void callme() {
    System.out.println("Inside B"s callme method");
  }
}
class C extends A {
  void callme() {
    System.out.println("Inside C"s callme method");
  }
}
class Dispatch {
  public static void main(String args[]) {
    A a = new A(); // object of type A
    B b = new B(); // object of type B
    C c = new C(); // object of type C
    A r; // obtain a reference of type A
    r = a; // r refers to an A object
    r.callme(); // calls A"s version of callme
    r = b; // r refers to a B object
    r.callme(); // calls B"s version of callme
    r = c; // r refers to a C object
    r.callme(); // calls C"s version of callme
  }
}





Polymorphism

It means the ability of a single variable of a given type to be used to reference objects of different types and to automatically call the method that is specific to the type of object the variable references. (Ivor Horton"s Beginning Java 2, JDK 5 Edition by Ivor Horton Wrox Press 2005 )

polymorphism works with derived class objects.



import java.util.Random;
class Animal {
  public Animal(String aType) {
    type = new String(aType);
  }
  public String toString() {
    return "This is a " + type;
  }
  public void sound(){
    System.out.println("Sound for an animal");
  }
  private String type;
}
class Dog extends Animal {
  public Dog(String aType){
   super(aType); 
  }
  public void sound() {
    System.out.println("Woof Woof");
  }
}
class Cat extends Animal {
  public Cat(String aName) {
    super("Cat"); 
    name = aName; 
    breed = "Unknown"; 
  }
  public Cat(String aName, String aBreed) {
    super("Cat"); 
    name = aName; 
    breed = aBreed; 
  }
  public String toString() {
    return super.toString() + "\nIt"s " + name + " the " + breed;
  }
  public void sound() {
    System.out.println("Miiaooww");
  }
  private String name;
  private String breed;
}
class Duck extends Animal {
  public Duck(String aName) {
    super("Duck"); 
    name = aName; 
    breed = "Unknown";
  }
  public Duck(String aName, String aBreed) {
    super("Duck"); 
    name = aName; 
    breed = aBreed;
  }
  public String toString() {
    return super.toString() + "\nIt"s " + name + " the " + breed;
  }
  public void sound() {
    System.out.println("Quack quackquack");
  }
  private String name;
  private String breed;
}
public class MainClass {
  public static void main(String[] args) {
    Animal[] theAnimals = { new Dog("A"), 
                            new Cat("C", "D"),
                            new Duck("E", "F") };
    Animal petChoice;
    Random select = new Random();
    for (int i = 0; i < 5; i++) {
      petChoice = theAnimals[select.nextInt(theAnimals.length)];
      System.out.println("\nYour choice:\n" + petChoice);
      petChoice.sound();
    }
  }
}



Your choice:
This is a A
Woof Woof
Your choice:
This is a Duck
It"s E the F
Quack quackquack
Your choice:
This is a Duck
It"s E the F
Quack quackquack
Your choice:
This is a Duck
It"s E the F
Quack quackquack
Your choice:
This is a Duck
It"s E the F
Quack quackquack


Using run-time polymorphism.

class Figure {
  double dim1;
  double dim2;
  Figure(double a, double b) {
    dim1 = a;
    dim2 = b;
  }
  double area() {
    System.out.println("Area for Figure is undefined.");
    return 0;
  }
}
class Rectangle extends Figure {
  Rectangle(double a, double b) {
    super(a, b);
  }
  // override area for rectangle
  double area() {
    System.out.println("Inside Area for Rectangle.");
    return dim1 * dim2;
  }
}
class Triangle extends Figure {
  Triangle(double a, double b) {
    super(a, b);
  }
  // override area for right triangle
  double area() {
    System.out.println("Inside Area for Triangle.");
    return dim1 * dim2 / 2;
  }
}
class FindAreas {
  public static void main(String args[]) {
    Figure f = new Figure(10, 10);
    Rectangle r = new Rectangle(9, 5);
    Triangle t = new Triangle(10, 8);
    Figure figref;
    figref = r;
    System.out.println("Area is " + figref.area());
    figref = t;
    System.out.println("Area is " + figref.area());
    figref = f;
    System.out.println("Area is " + figref.area());
  }
}