多态性2

  1 public class Demo3 {
  2 public boolean equalArea(Father d1,Father d2){
  3     return d1.findArea()==d2.findArea();
  4 
  5 
  6 }
  7     public void Area(Father e){
  8         if (e instanceof Circle){
  9             e.findArea();
 10             System.out.println("圆的面积为:"+e.findArea());
 11         }else if (e instanceof MyRectangle){
 12             e.findArea();
 13             System.out.println("矩形的面积为:"+e.findArea());
 14         }
 15 
 16     }
 17 
 18     public static void main(String[] args) {
 19         Demo3 demo3=new Demo3();
 20         Father demo31=new Father("red",3);
 21         Father demo32=new Circle(4,"green",5);
 22         demo3.Area(new Circle(3,"黄色",10));
 23         demo3.Area(new MyRectangle(5,5,"绿色",8));
 24        // demo3.equalArea(demo31,demo32);
 25         boolean isEquals=demo3.equalArea(demo31,demo32);
 26         System.out.println(isEquals);
 27     }
 28 }
 29 
 30 class Father{
 31        private   String color;
 32        private double weight;
 33        public Father(String color,double weight){
 34         }
 35 
 36     public String getColor() {
 37         return color;
 38     }
 39 
 40     public void setColor(String color) {
 41         this.color = color;
 42     }
 43 
 44     public double getWeight() {
 45         return weight;
 46     }
 47 
 48     public void setWeight(double weight) {
 49         this.weight = weight;
 50     }
 51     public double findArea(){
 52            return 0;
 53     }
 54 }
 55 //圆的面积
 56 class Circle extends Father{
 57     private double radius;
 58     public Circle(double radius,String color,double weight){
 59         //子类进行有参构造时,父类构造器如果为有参构造,
 60         //且无空参构造器,则子类调用时必须显式的声明调用super(形参名称),
 61         // 且将子类新的形参进行this.形参=属性名称进行声明
 62     super(color,weight);
 63     this.radius=radius;
 64     }
 65 
 66     public double getRadius() {
 67         return radius;
 68     }
 69 
 70     public void setRadius(double radius) {
 71         this.radius = radius;
 72     }
 73     public double findArea(){
 74         return Math.PI*radius*radius;//计算圆的面积
 75     }
 76 }
 77 //计算矩形面积
 78 class MyRectangle extends Father{
 79     private double width;
 80     private double height;
 81     public MyRectangle(double width,double height,String color,double weight){
 82         super(color,weight);
 83         this.width=width;
 84         this.height=height;
 85     }
 86 
 87     public double getWidth() {
 88         return width;
 89     }
 90 
 91     public void setWidth(double width) {
 92         this.width = width;
 93     }
 94 
 95     public double getHeight() {
 96         return height;
 97     }
 98 
 99     public void setHeight(double height) {
100         this.height = height;
101     }
102 public double findArea(){
103         return width*height;
104 }
105 }

子类调用父类有参构造器时注意super(形参名),以及this声明自身形参,

posted @ 2021-09-16 19:32  tiiiiii  阅读(46)  评论(0)    收藏  举报