1.定义一个基类Shape,在此基础上派生出Rectangle和Circle,二者都有getArea()函数计算对象的面积。使用Rectangle类创建一个派生类Square。
1 //基类Shape 2 class Shape { 3 public double getArea() { 4 return 0; 5 } 6 } 7 //Rectangle类继承Shape类 8 class Rectangle extends Shape { 9 private double len; 10 private double width; 11 public Rectangle(double len, double width) { 12 super(); 13 this.len = len; 14 this.width = width; 15 } 16 public double getArea() { 17 return len * width; 18 } 19 } 20 //Circle类继承Shape类 21 class Circle extends Shape { 22 private double r; 23 public Circle(double r) { 24 super(); 25 this.r = r; 26 } 27 public double getArea() { 28 return 3.14 * r * r; 29 } 30 } 31 //Square类继承Rectangle类 32 public class Square extends Rectangle { 33 public Square(double len, double width) { 34 super(len, width); 35 } 36 public static void main(String[] args) { 37 Shape p = new Rectangle(3, 6); 38 System.out.println("The area of the rectangle is " + p.getArea()); 39 p = new Circle(3); 40 System.out.printf("The area of the circle is %.2f\n", p.getArea()); 41 p = new Square(4, 4); 42 System.out.println("The area of the square is " + p.getArea()); 43 } 44 }
2.定义一个哺乳动物类Mammal,再由此派生出狗类Dog,定义一个Dog类的对象,观察基类和派生类的构造函数的调用顺序。
1 //父类Mammal类 2 class Mammal{ 3 private String name; 4 private int age; 5 public Mammal(String name, int age) { 6 this.name=name; 7 this.age=age; 8 System.out.println("构造哺乳动物类"); 9 } 10 public String getName() { 11 return name; 12 } 13 public int getAge() { 14 return age; 15 } 16 } 17 //Dog类继承Mammal类 18 public class Dog extends Mammal{ 19 private int leg; 20 public Dog(String name, int age, int leg) { 21 super(name, age); 22 this.leg=leg; 23 System.out.println("构造狗类"); 24 } 25 public void display() { 26 System.out.println("Name:"+getName()); 27 System.out.println("Age:"+getAge()); 28 System.out.println("Leg:"+leg); 29 } 30 public static void main(String[] args) { 31 Dog p=new Dog("Sera",5,4); 32 p.display(); 33 } 34 }