简体   繁体   English

从抽象类继承

[英]Inheriting from an abstract class

Lets assume that I have 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();

}

I also have two classes that inherit from it: 我也有两个继承自它的类:

  1. HandicappedCustomer , where I want to set the price to be 0. HandicappedCustomer ,我要将价格设置为0。
  2. RegularCustomer , where I want to set the price to be 100. RegularCustomer ,我要将价格设置为100。

Now if I create an instance of each of these classes and called getPrice() , I return 0 for both. 现在,如果我为每个类创建一个实例并称为getPrice() ,则两个实例均返回0。 What is the easiest way to make it return 0 and 100 when I call getPrice() for each corresponding instance of the class? 当我为类的每个对应实例调用getPrice()时,使它返回0和100的最简单方法是什么?

When I try to call setPrice(100) inside the RegularCustomer class, I see that it doesn't work. 当我尝试在RegularCustomer类内调用setPrice(100) ,我发现它不起作用。 To put it plainly, I want to have the following code in my main: 简而言之,我要在主机中包含以下代码:

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

And to have it return: 并使其返回:

0 0
100 100

If you want getPrice to always return 100 for regular customers and always return 0 for handicapped customers, you would write 如果您希望getPrice对于常规客户始终返回100,对于残障客户始终返回0,则应编写

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

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

but that doesn't exactly sound like what you want (at least for regular customers) since you included setPrice in your design. 但这听起来并不完全像您想要的(至少对于普通客户而言),因为您在设计中包括了setPrice Sounds like you want those values to be returned initially . 听起来好像您希望这些值最初返回。 In that case: 在这种情况下:

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

and

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

should do the trick. 应该可以。

They will both inherit setPrice in case you want to change them later, and they will both inherit getPrice so everything should work as expected. 它们都将继承setPrice以防您稍后更改它们,并且它们都将继承getPrice因此所有操作均应按预期进行。

Live demo at ideone . ideone现场演示

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

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