I have a certain question that has been a bit difficult for me to understand regarding this topic. It happens that a subclass does not inherit the private attributes of a class. However, I can use methods to access them.
What intrigues me is, does it inherit them indirectly? Consider this case:
package Inheritance;
public class Bike {
private String model;
void setModel(String model){
this.model = model;
}
String getModel(){
return model;
}
}
package Inheritance;
public class MountainBike extends Bike{
public static void main(String[] args){
MountainBike mountainBike = new MountainBike();
mountainBike.setModel("rtx500");
System.out.println(mountainBike.getModel());
}
}
What happens is that I create an object of type MountainBike. Theoretically, I should not be able to access the attributes because I don’t inherit them from the superclass. I use a setter to initialize it as its own (not belonging to an object of the superclass but to the subclass). How is it possible for the subclass to initialize it as its own attribute (i.e., inherited) if private fields are not supposed to be inherited?
thanks for your help!
PEREZ MONSIVAIS JOSE DE JESUS is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.