繁体   English   中英

摘要 Class getter 和 setter 用法

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM