Bob Ross Bob Ross - 6 months ago 5
Java Question

Need assistance with inheritance logic

If I have a subclass called AmericanFender which extends Fender, while Fender extends the superclass BassGuitars, why would something like

AmericanFender amFen = new AmericanFender();

not work out to amFen.brand equaling "Fender" when

Fender fen = new Fender()
fen.brand = Fender;

Instead amFen.brand is coming out to be null. I thought since AmericanFender extends Fender, it inherits the instance variables of Fender(which those are inherited from BassGuitars) as long as they are public? I'm obviously thinking about inheritance incorrectly, so could someone steer me in the right direction? Much appreciated!


In inheritance, AmericanFender DOES inherit the instance variables of Fender. This means it will have the same fields as Fender. This does NOT mean it will have the same values in these fields. It will have an empty field called brand, which is what you are seeing.

If you want it to inherit the value, you could make a method inside your Fender class:

public String getBrand() {
 return "Fender";

And then you can call:

AmericanFender f = new AmericanFender();