There is a characteristic of inheritance, that is, subclasses cannot access parent classprivatefield or privatemethod. For example, the Student class cannot accessPersonnameandagefield:
class Person {
private String name;
private int age;
}
classStudent extends Person {
public String hello() {
return “Hello, “ + name; // Compile error: cannot accessname Field
}
} span>
This weakens the role of inheritance. In order to allow subclasses to access the fields of the parent class, we need to change private to protected. Fields modified with protected can be accessed by subclasses:
class Person {
protected String name;
protected int age;
}
classStudent extends Person {
public String hello() {
return “Hello, “ + name; // OK!
}
}
Therefore,protected Keywords can control the access rights of fields and methods within the inheritance tree, a protected Fields and methods can be accessed by its subclasses and subclasses of subclasses, which we will explain in detail later.
2. The use of super
superThe keyword indicates the parent class (super class). When a subclass refers to a field of the parent class, you can use super.fieldName. For example:
class Student extends Person {
public String hello() {
return “Hello, “ + super.name;
}
}
The above code execution will cause compilation errors, the student construction method cannot call the Person construction method.
Analysis: The construction method of any class must first construct the construction method of the parent class. If there is no explicit call to the constructor of the parent class, the compiler will automatically add a sentence of super() for us, so the constructor of the Student class is actually like this
The writing method in the Student class is
Summary: If the parent class does not have a default constructor, the subclass must explicitly callsuper() and give parameters to let the compiler locate A suitable constructor. At the same time, the subclass will not inherit any parent class construction method, the subclass default construction method is automatically generated by the compiler, not inherited