I'm having trouble understanding inheritance. In the code below, why doesn't the inherited method access the field in the subclass? Is there any way to access the subclass field without overriding the inherited method?
class Fish {
private String fishType = "Fish";
public String getFishType() {
return fishType;
}
}
class Marlin extends Fish {
private String fishType = "Marlin";
}
public class InheritanceTest {
public static void main(String[] args) {
Fish fish1 = new Fish();
Fish marlin1 = new Marlin();
System.out.println(fish1.getFishType());
System.out.println(marlin1.getFishType());
}
}
This code prints
Fish
Fish
but I was expecting
Fish
Marlin
Everyone seems to be answering based on the strings being private, yet even if I change the fields to public I still have the problem. The question isn't about inheriting private fields.
Please see updated code below.
class Fish {
public String fishType = "Fish";
public String getFishType() {
return fishType;
}
}
class Marlin extends Fish {
public String fishType = "Marlin";
}
public class InheritanceTest {
public static void main(String[] args) {
Fish fish1 = new Fish();
Marlin marlin1 = new Marlin();
System.out.println(fish1.getFishType());
System.out.println(marlin1.getFishType());
}
}
The output and my expectations are the same as above.