我知道,無論實際的對象是什麼,引用變量指的是,我可以調用引用的方法取決於變量的聲明類型(在代碼的第15行)。我想知道爲什麼這樣。爲什麼類用戶不能使用Shape類型的引用變量s來調用它的子類方法drawCircle()?爲什麼我們不能使用超類的引用變量來訪問其子類的方法(在超類中不可用的方法)?
public class Shape{
public void displayShape(){
System.out.println("shape displayed");
}
public class Circle extends Shape{
public void drawCircle(){
System.out.println("circle drawn");
}
public class Test{
p.s.v.main(String[] a){
Circle c=new Circle();
Shape s=new Shape();
display(c);
display(s);
public void display(Shape myShape){
myShape.displayShape();//possible for ref variable c and s
myShape.drawCircle();//not possible for reference var s
}
}
}
u能爲我提供的對象級別會發生什麼解釋?我是新來的Java。
更正您的代碼並編寫完整代碼不要使用像這裏使用的快捷方式「p.s.v」而不是寫入public static void main(String args [])。另外還有更多的錯誤,所以請重新構造一次代碼。如果要實現這樣的功能,Java中不允許嵌套函數使用Java 8的lambda表達式。 –