I have a parent class that has 2 private instance fields but my child class which has no instance fields 'magically' creates 2 instance fields.
public class Parent
{
private String firstName;
public String lastName;
private int age;
public Parent()
{
System.out.println("No-Parameter Constructor");
}
public Parent(String firstName, String lastName, int age)
{
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
public String toString()
{
return "firstName: " + firstName + " lastName: " + lastName + " age: " + age;
}
public String getFN()
{
return firstName;
}
}
public class Student extends Parent
{
public Student(String firstName, String lastName, int age)
{
super(firstName, lastName, age);
}
public static void main(String[] args)
{
Parent p = new Parent("Logi", "Tech", 42);
Student s = new Student("Logi", "Camera", 21);
System.out.println(p);
System.out.println(s);
System.out.println(p);
System.out.println(p.getFN());
}
}
Output:
firstName: Logi lastName: Tech age: 42
firstName: LogiStudent lastName: Camera age: 21
firstName: Logi lastName: Tech age: 42
LogiStudent
You are not accessing private fields from the Student class. Just look at your code - nowhere in the body of class Student extends Parent {}
do you refer to those fields in any way.
class Student extends Parent
is java-ese for: "Let's define this new concept called Student
. Begin by taking absolutely every single last thing Parent has, and then bolt, on top of all that, a few more things".
In other words, if Parent has the field 'age
, then so does Student
.
accessibility is almost entirely unrelated to this notion; accessibility (private
) is about which code (NOT which instance!!) is allowed to directly interact with things. Given that the age
field is private
, whilst every instance of Student
has that field, the code located in Student.java
cannot touch that field directly. It is of course free to invoke a method that its superclass does allow access to (such as the toString
method which is public
) and then observe as IT touches those fields. That's not 'direct access', that's indirect, and that is fine.
Similarly, Student can invoke getFN()
anywhere it wants, and thus get the first name. It cannot, however, set the firstname, unless Parent decides to add a void setFirstName(String fn) { this.firstName = fn; }
method, of course.