为什么java多态性在我的示例中不起作用
我有以下4个java类: 一, 二, 三, 四, 我得到了输出: r1的面积=6.0 pr1的面积=24.0 cr1的面积=6.0颜色=红色 多态射 r2的面积=2.0 pr2的面积=8.0 cr2的面积=2.0颜色=透明***为什么java多态性在我的示例中不起作用,java,polymorphism,subclass,superclass,Java,Polymorphism,Subclass,Superclass,我有以下4个java类: 一, 二, 三, 四, 我得到了输出: r1的面积=6.0 pr1的面积=24.0 cr1的面积=6.0颜色=红色 多态射 r2的面积=2.0 pr2的面积=8.0 cr2的面积=2.0颜色=透明*** P> 为什么认为CR2为ReCt(超类),而“透明”颜色不是Clct(子类)“蓝色”?< /强> < P>这是使用可见字段的问题之一-你最终使用它们… 在Rect和CRect中都有一个color字段。字段不是多态的,因此当您使用cr2.color时,它使用Rect中
<> P> <强>为什么认为CR2为ReCt(超类),而“透明”颜色不是Clct(子类)“蓝色”?< /强> < P>这是使用可见字段的问题之一-你最终使用它们… 在
Rect
和CRect
中都有一个color
字段。字段不是多态的,因此当您使用cr2.color
时,它使用Rect
中声明的字段,该字段始终设置为“透明”
您的
CRect
类不应该有自己的color
字段-它应该向超类构造函数提供颜色。一个矩形有两个不同的color
字段是没有意义的-它可以有borderColor
和fillColor
,当然-但是color
太模糊了…您应该在子类的构造函数中包含一个显式的super()
调用:
public CRect(double w, double h ,String c) {
super(w, h);
width=w;
height=h;
color=c;
}
cr2.area()
将调用CRect.area()
但cr2.color
将使用字段Rect.color
。您应该使用函数样式getArea(),并具有CRect.getColor(){return color;}
以及Rect.getColor(){return color;}
您需要一个getColor()
method.or实例变量不会被重写,但它们在子类的s@GanGnaMStYleOverFlowErroR:我不确定我是否理解您的评论,但重写字段的想法根本不适用,因为字段上没有多态性…是的,多态性不适用于字段(实例变量)
,这难道不意味着它们不能被重写吗???@GangnamStyleOverflower:是的,它们不能被重写,因为多态性根本不适用。它也不适用于静态变量,静态变量也是字段
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;
}
}
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;
}
}
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);
}
}
area of r1=6.0
area of pr1=24.0
area of cr1=6.0 color = RED
POLY_MORPHISM
area of r2=2.0
area of pr2=8.0
area of cr2=2.0 color = transparent***
public CRect(double w, double h ,String c) {
super(w, h);
width=w;
height=h;
color=c;
}