【问题标题】:why java polymorphism not work in my example为什么 java 多态在我的示例中不起作用
【发布时间】:2012-11-24 17:57:20
【问题描述】:

我有这 4 个 java 类: 1

public class Rect {
    double width;
    double height;
    String color;

    public Rect( ) {
        width=0;
        height=0;
        color="transparent";      
    }

    public Rect( double w,double h) {
        width=w;
        height=h;
        color="transparent";
    }

    double area()
    {
        return  width*height;
    } 
}

2

public class PRect extends Rect{
    double depth;

    public PRect(double w, double h ,double d) {
        width=w;
        height=h;
        depth=d;
    }

    double area()
    {
        return  width*height*depth;
    }     
}

3

public class CRect extends Rect{ 
    String color;

    public CRect(double w, double h ,String c) {
        width=w;
        height=h;
        color=c;
    }

    double area()
    {
        return  width*height;
    }     
}

4

public class test {

    public test() { }

    public static void main(String[] args) {  
        Rect r1=new Rect(2,3);
        System.out.println("area of r1="+r1.area());

        PRect pr1=new PRect(2,3,4);
        System.out.println("area of pr1="+pr1.area());


        CRect cr1=new CRect(2,3,"RED");
        System.out.println("area of cr1="+cr1.area()+"  color = "+cr1.color);


        System.out.println("\n POLY_MORPHISM ");
        Rect r2=new Rect(1,2);
        System.out.println("area of r2="+r2.area());

        Rect pr2=new PRect(1,2,4);
        System.out.println("area of pr2="+pr2.area());


        Rect cr2=new CRect(1,2,"Blue");
        System.out.println("area of cr2="+cr2.area()+"  color = "+cr2.color); 

    }
}

我得到了输出:

r1=6.0的面积 pr1的面积=24.0 cr1=6.0 颜色的面积 = RED POLY_MORPHISM r2=2.0 的面积 pr2的面积=8.0 cr2的面积=2.0 颜色=透明***

为什么将 cr2 视为 Rect(超类)并具有“透明”颜色而不是 CRect(子类)与“蓝色”颜色?

【问题讨论】:

  • 你需要一个getColor() 方法。

标签: java polymorphism subclass superclass


【解决方案1】:

这是使用可见字段的问题之一 - 你最终会使用它们...

RectCRect 都有一个 color 字段。字段不是多态的,因此当您使用cr2.color 时,它使用在Rect 中声明的字段,该字段始终设置为"transparent"

您的CRect 类应该拥有自己的color 字段 - 它应该为超类构造函数提供颜色。一个矩形有两个不同的color 字段是没有意义的——当然,它可以有borderColorfillColor——但只是color 太模棱两可了......

【讨论】:

  • 或实例变量未被覆盖,但它们在您的子类中可见
  • @GanGnaMStYleOverFlowErroR:我不确定我是否理解您的评论,但是覆盖字段的想法根本不适用,因为字段没有多态性...
  • 是的,polymorphism doesn't apply to fields(instance variables),这不是说它们不能被覆盖吗??
  • @GanGnaMStYleOverFlowErroR:是的,它们不能被覆盖,因为多态性根本不适用。它也不适用于静态变量,它们也是字段。
  • 这就是我的第一条评论所暗示的,:P
【解决方案2】:

您应该在子类的构造函数中包含一个显式的super() 调用:

public CRect(double w, double h ,String c) {
    super(w, h);
    width=w;
    height=h;
    color=c;
}

【讨论】:

    【解决方案3】:

    cr2.area() 将调用 CRect.area()cr2.color 将使用字段 Rect.color。您应该使用函数样式 getArea() 并拥有 CRect.getColor() { return color; } 以及 Rect.getColor() { return color; }

    【讨论】:

      猜你喜欢
      • 2016-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-28
      • 2015-11-08
      • 2018-11-14
      • 2014-09-05
      • 2016-02-18
      相关资源
      最近更新 更多