問一個關(guān)于多態(tài)和繼承相關(guān)的問題。
public?abstract?class?Shape?{ public?abstract?void?getPerimeter(); public?abstract?void?getArea(); ?}
這是我先實(shí)現(xiàn)的一個抽象的父類Shape;
public?class?Rectangle?extends?Shape?{ int?length; int?wide; public?void?getPerimeter()?{ ????????System.out.println("矩形的周長為:"+(length+wide)*2); ?} ?public?void?getArea()?{ ? System.out.println("矩形的面積為:"+length*wide); ?} }
這是我實(shí)現(xiàn)的一個繼承Shape父類的一個子類Rectangle;
現(xiàn)在我用多態(tài)的方法 Shape rectangle = new Rectangle();? 用父類引用子類
public?class?Initial?{ public?static?void?main(String[]?args)?{ Shape?rectangle?=?new?Rectangle(); rectangle.length?=?10; rectangle.width?=?5; Shape?circle?=?new?Circle(); ????} }
那么問題來了,我要怎樣才能給子類中的length和width賦值?
我上面的那兩個賦值是錯的;
希望你能幫我
2019-02-22
這個問題出現(xiàn)的原因可以在eclipse的報錯說明里面找到,大概就是Shape類中沒有l(wèi)ength和width這兩個變量,所以無法進(jìn)行賦值.
我們可以在Shape類中加上這兩個變量,或者將第三段代碼的第三行用如下代碼替代:
2019-03-26
你可以在子類里面給他賦值?如?int?lenght=10;int?wide=5;這樣就引用進(jìn)去了