Java中的继承和多态性研究进展

Java中的继承和多态性研究进展,java,inheritance,polymorphism,Java,Inheritance,Polymorphism,我正在准备期末考试,我遇到了一个关于理解继承和多态性的示例问题。我必须解释每一行是否会产生编译器错误(C)、运行时错误(R)或运行正常(F)。我写下并解释了每一行的结果,但我希望有人提供或指出我在回答中的错误,或许可以纠正我的误解 鉴于以下类别: public abstract class Shape{ protected double area; public double getArea(){ return area; } public abstract void computeArea()

我正在准备期末考试,我遇到了一个关于理解继承和多态性的示例问题。我必须解释每一行是否会产生编译器错误(C)、运行时错误(R)或运行正常(F)。我写下并解释了每一行的结果,但我希望有人提供或指出我在回答中的错误,或许可以纠正我的误解

鉴于以下类别:

public abstract class Shape{
protected double area;
public double getArea(){
return area;
}
public abstract void computeArea();
}

这是我写的:

Shape s = new Rectangle(); 
这条线很好,因为您正在创建一个看起来像矩形的形状s,因为矩形扩展了形状。但是,在这种情况下,s只能从类形状访问方法(如果存在过多的方法或构造函数,它通常会从类矩形访问其他方法)。这条线很好(F)

我很难理解这条线,但我认为这条线也很好(F),因为你要把s形状转换成矩形。也就是说,Shape s也可以使用来自类Rectangle的方法,这与上面的行不同

Rectangle r2 = s; 
在这里,您正在将s转换为矩形。这将导致编译器错误(C),因为无法将父类(s是类形状的对象)强制转换为其子类(类矩形)

这一行很好(F),因为您刚刚创建了一个名为rar的数组,其长度为2

s.setS1(3.0); 
因为类矩形中的方法setS1没有限制。由于s能够访问类Rectangle,因为我们从
rectangler=(Rectangle)s行将其转换为一种类型的矩形这一行也很好(F)

此行将导致运行时错误(R),因为computeArea方法为null,因为区域从未初始化?我不确定这件事

rar[0].computeArea(); 
在这里,线路将正常工作(F)。但是,计算机区域中没有任何内容,因为s1和s2尚未初始化


无论如何,任何投入都是值得赞赏的。谢谢你的回答。如果你喜欢我的答案,为什么不把它标为接受呢?对不起。我是新来的。我还在想办法。谢谢你的投入。
Shape s = new Rectangle(); // Works fine
Rectangle r = (Rectangle)s; // Works fine
Rectangle r2 = s; // Needs typecasting, Compile fail
Rectangle[] rar = new Rectangle[1]; // Fine, array of length 1
s.setS1(3.0); // Shape doesn't know about setS1(), compile fail
s.computeArea(); // Works fine, though abstract method, known that an solid class has to implement
rar[0].computeArea(); // Run time NullPointerException, rar[0] not initialized
r.s1 = 4.5; // s1 is private, compile error
r.setS1(5.0); // works fine
r.setS2(3.0); // works fine
s.getArea(); // works fine
System.out.println(r.computeArea()); // Can't print void method, compile error
r = null; // Works fine
rar[1] = new Rectangle(); // Runtime ArrayIndexOutOfBoundsException, your array size is 1
System.out.println(Rectangle.name); // Works fine
Rectangle[] rar = new Rectangle[1];
s.setS1(3.0); 
s.computeArea(); 
rar[0].computeArea(); 
Shape s = new Rectangle(); // Works fine
Rectangle r = (Rectangle)s; // Works fine
Rectangle r2 = s; // Needs typecasting, Compile fail
Rectangle[] rar = new Rectangle[1]; // Fine, array of length 1
s.setS1(3.0); // Shape doesn't know about setS1(), compile fail
s.computeArea(); // Works fine, though abstract method, known that an solid class has to implement
rar[0].computeArea(); // Run time NullPointerException, rar[0] not initialized
r.s1 = 4.5; // s1 is private, compile error
r.setS1(5.0); // works fine
r.setS2(3.0); // works fine
s.getArea(); // works fine
System.out.println(r.computeArea()); // Can't print void method, compile error
r = null; // Works fine
rar[1] = new Rectangle(); // Runtime ArrayIndexOutOfBoundsException, your array size is 1
System.out.println(Rectangle.name); // Works fine