简体   繁体   中英

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.
  2. RegularCustomer , where I want to set the price to be 100.

Now if I create an instance of each of these classes and called getPrice() , I return 0 for both. What is the easiest way to make it return 0 and 100 when I call getPrice() for each corresponding instance of the class?

When I try to call setPrice(100) inside the RegularCustomer class, I see that it doesn't work. 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
100

If you want getPrice to always return 100 for regular customers and always return 0 for handicapped customers, you would write

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. 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.

Live demo at ideone .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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