繁体   English   中英

从抽象类继承

[英]Inheriting from an abstract class

假设我有一个抽象类:

public abstract class Customer {
  private int price;

  public void setPrice(int price) {
    this.price = price;
  }

  public int getPrice() {
    return price;
  }

  public abstract void pay(int n);
  public abstract void occupySpace();

}

我也有两个继承自它的类:

  1. HandicappedCustomer ,我要将价格设置为0。
  2. RegularCustomer ,我要将价格设置为100。

现在,如果我为每个类创建一个实例并称为getPrice() ,则两个实例均返回0。 当我为类的每个对应实例调用getPrice()时,使它返回0和100的最简单方法是什么?

当我尝试在RegularCustomer类内调用setPrice(100) ,我发现它不起作用。 简而言之,我要在主机中包含以下代码:

Customer a = new HandicappedCustomer(); 
Customer b = new RegularCustomer();
System.out.println(a.getPrice());
System.out.println(b.getPrice());

并使其返回:

0
100

如果您希望getPrice对于常规客户始终返回100,对于残障客户始终返回0,则应编写

class RegularCustomer extends Customer {
    public int getPrice() {
        return 100;
    }
}

class HandicappedCustomer extends Customer {
    public int getPrice() {
        return 0;
    }
}

但这听起来并不完全像您想要的(至少对于普通客户而言),因为您在设计中包括了setPrice 听起来好像您希望这些值最初返回。 在这种情况下:

class RegularCustomer extends Customer {
    public RegularCustomer() {
        setPrice(100);
    }
}

class HandicappedCustomer extends Customer {
    public HandicappedCustomer() {
        setPrice(0);
    }
}

应该可以。

它们都将继承setPrice以防您稍后更改它们,并且它们都将继承getPrice因此所有操作均应按预期进行。

ideone现场演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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