[英]Abstract Class getter and setter usage
早上好,
首先感恩節快樂。 我有一個關於我打算如何創建抽象模型的問題,我使用抽象 class 作為基礎 class 然后是子類,這樣使用它可以嗎?
我做了谷歌並找到了一些樣本,但沒有一個與我的做法完全一樣。
public abstract class Vehicle {
String type;
String color;
public abstract getType();
public abstract setType(String type);
public abstract String getColor();
public abstract setColor(String color);
}
然后在我的子類中,我可以做這樣的事情:
public class Truck extends Vehicle {
String pickupBed;
public setPickupBed(String pickupBed) {
this.pickupBed = pickupBed;
}
public getPickupBed(String pickupBed) {
return pickupBed;
}
public setType(String type) {
this.type = type;
}
public getType(String type) {
return type;
}
public setColor(String color) {
this.color = color;
}
public getColor() {
return color;
}
}
而另一個class,除了汽車,沒有皮卡床。
public class Car extends Vehicle {
public setType(String type) {
this.type = type;
}
public getType(String type) {
return type;
}
public setColor(String color) {
this.color = color;
}
public getColor() {
return color;
}
}
您可以在抽象 class 中執行所有操作,您可以在普通 class 中執行所有操作,但只能使用構造函數創建新的 object。
這意味着您可以簡單地將子類中的 getter 和 setter 復制並粘貼到父 class 中。
根據您的實現目標和風格理念,您甚至可以使這些 getter/setter 成為final ,這意味着子類根本無法覆蓋它們。 這看起來像這樣: public final String getType(){...}
。
只有當您需要更改 getiin 的行為和設置變量時,您才需要創建抽象的 getter 和 setter。 如果所有子類都使用相同的 getter 和 setter 實現 - 您需要在抽象 class 中創建 getter 和 setter:
public abstract class Vehicle {
protected String type;
protected String color;
public String getType(){
return type;
};
public String setType(String type){
this.type = type;
}
........
}
在任何情況下,如果您將來需要為 setter/getter 包含任何邏輯 - 您可以覆蓋現有的 getter/setter:
public class Car extends Vehicle{
public setType(String type){
if (type.equals("type1")){
this.type = type + "_1";
} else {
this.type = type + "_2";
}
}
public String getType(String type){
return "{" + this.type + "}";
}
}
只有當你想強制類子實現一些邏輯時,你才需要添加抽象方法,fe:
public abstract class Vehicle {
protected String type;
protected String color;
public String getType(){
return type;
};
public String setType(String type){
this.type = type;
}
public String getTypeDescription(){
return "Type description: " + generateDescription();
}
protected abstract String generateTypeDescription();
........
}
public class Car extends Vehicle{
String generateTypeDescription(){
return "bla...bla..";
}
}
您的超類(車輛)的 getter 和 setter 不應該是抽象的。 超級 class 中的變量必須是私有的或公共的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.