I have a question regarding inheritance in Java. If I have this base class
class Parent {
private String lastName;
public Parent() {
lastName = "Unassigned";
}
public String getLastName( ) {
return lastName;
}
public void setLastName(String name) {
lastName = name;
}
}
And this subclass
class Child extend Parent {
private String surName;
public Child(String name) {
surName = name;
}
public void setFullName(String first, String last) {
surName = first;
..... = last;
}
}
I want to make a method now in the subclass which can change both surname and lastname in a method. So I wonder how I can the private member lastname which is to be found in the base class. Should I use the setLastName() method which is inherit, or can I access the variable without having going through that way?
I also have question regarding if I was to override the setLastName() method in baseclass. How do I access the private member lastname which is in the baseclass then?
You cannot access private members from an inherited class. You can either make them protected or use the setter (the latter one is preferable in my view).
You can override setLastName() in the inherited class and change the private member using the setter of the base class by means of the “super”-keyword (super.setLastName(“something”)).