Bob Ross
Bob Ross

Reputation: 61

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(); System.out.println(amFen.brand);

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!

Upvotes: 1

Views: 28

Answers (2)

Efthimis_28
Efthimis_28

Reputation: 363

If you could post a whole part of your code maybe the question would be more specific, however what you might have misunderstood about inheritance is that if a class inherits another class, then the subclass inherits the same fields from the super class but not the value inside the field. For example:

class kid extends parent {

if you have a field named haircolor in the parent class and

parent.haircolor = brown;

then the kid also has a haircolor characteristic but it doesn't equal brown. It equals null until you initialize it.

Upvotes: 0

nhouser9
nhouser9

Reputation: 6780

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();
System.out.println(f.getBrand());

Upvotes: 1

Related Questions