GeometricObject
package 多态性练习;
public class GeometricObject {
protected String color;
protected double weight;
protected GeometricObject(String color,double weight) {
this.color = color;
this.weight = weight;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public double findArea() {
return 0;
}
}
Circle
package 多态性练习;
public class Circle extends GeometricObject{
private double radius;
protected Circle(double radius,String color, double weight) {
super(color, weight);
this.radius = radius;
}
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
public double findArea() {
return Math.PI * radius * radius;
}
}
MyRectangle
package 多态性练习;
public class MyRectangle extends GeometricObject{
private double width;
private double height;
protected MyRectangle(double width,double height,String color, double weight) {
super(color, weight);
this.width = width;
this.height = height;
}
public double getWidth() {
return width;
}
public void setWidth(double width) {
this.width = width;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public double findArea() {
return width * height;
}
}
GeometricTest
package 多态性练习;
public class GeometricTest {
public static void main(String[] args) {
GeometricTest t = new GeometricTest();
t.equalArea(new Circle(2,"blue",45), new MyRectangle(4, 5, "red", 96));
t.displayGeometricObject(new Circle(2, "blue", 45));
t.displayGeometricObject(new MyRectangle(8, 4, "black", 8));
}
public void equalArea(GeometricObject g,GeometricObject o) {
if(g.findArea() == o.findArea())
System.out.println("面积相等");
System.out.println("面积不相等");
}
public void displayGeometricObject(GeometricObject g) {
System.out.println("面积为:" + g.findArea());
}
}
InstanceTest
package 多态性练习;
public class InstanceTest {
public static void main(String[] args) {
InstanceTest t = new InstanceTest();
t.method(new Graduate());
}
public void method(Person e) {
System.out.println(e.getInfo());
if(e instanceof Graduate) {
System.out.println("a graduated student");
System.out.println("a student");
System.out.println("a person");
}
else if(e instanceof Student) {
System.out.println("a student");
System.out.println("a person");
}
else
System.out.println("a person");
}
}
class Person {
protected String name = "person";
protected int age = 50;
public String getInfo() {
return "Name: " + name + "\n" + "age: " + age;
}
}
class Student extends Person {
protected String school = "pku";
public String getInfo() {
return "Name: " + name + "\nage: " + age + "\nschool: " + school;
}
}
class Graduate extends Student {
public String major = "IT";
public String getInfo() {
return "Name: " + name + "\nage: " + age + "\nschool: " + school + "\nmajor:" + major;
}
}