Everything here is renamed and simplified.

I have a parent class (normalThing) with a method that displays some data about the instance, and another class (specialThing) extending the parent to include another instance variable (addedPrice).

I want my display method to say whether or not the instance is a specialThing, and if it is, to display the addedPrice. But because addedPrice belongs only to specialThing, I can't figure out how to code it!

void displayInfo(){
    StringBuilder d = new StringBuilder("Am I special? ");

    if(this instanceof specialThing){
        d.append("Yes, so I cost an extra " + this.addedPrice);
        //No, I didn't expect that to work, but I had hope
    }
    else d.append("Nope.");
    JOptionPane.showMessageDialog(null, d);
}

Is there any way to do this without essentially making a "could-be-addedPrice" variable in the normalThing class?

有帮助吗?

解决方案

You can achieve this by overriding displayInfo appropriately in child class. That is a better way because parent class should not try to know what are its children because number of child classes and their names are not in the control of parent class. People can extend the parent class in unexpected/unpredictable and uncontrolled manner. It will work well if you define displayInfo contract and enforce the child classes to implement it. Number of child classes does not matter. As long as displayInfo is implemented as per contract, OOP will take care of the rest :-)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top