[英]Calling super to store values, but using subclass constructor
是否可以使用父類以便為父類中的共享方法存儲公共值,但仍為子類使用單獨的構造函數(即,將來自不同子類的兩個構造函數的參數中的任意值k存儲到父類中? ,但仍要調用兩個子類中的各個構造函數)。
例如
在子類中:
public pictureImpl(Picture source, int x, int y, int height, int width) {
super(height, width);
"rest of constructor using all parameters"
}
在超類中:
public superPicture(int height, int width) {
heightValue = height;
widthValue = width;
}
在這里,仍然可以在子類的括號中使用該部分(即,即使在使用super存儲值之后,也可以調用構造函數的其余部分嗎?
這是基類的受保護構造函數的常見用例:
class Base {
private final int val;
protected Base(int val) {
this.val = val;
}
public int getVal() {
return val;
}
}
class Derived1 extends Base {
public Derived1(String name, int val) {
super(val);
...
}
...
}
class Derived2 extends Base {
public Derived2(int val, Date timestamp) {
super(val);
...
}
...
}
方法superPicture在超類上公開,並且繼承使用以擴展類。
您可以簡單地調用它。
如果覆蓋它,也可以使用super.superPicture(width,height);對其進行訪問。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.