Java neutron class calls the parent class construction method, matters needing attention

 

One characteristic of inheritance is that the subclass cannot access the private field or private method of the parent class . For example, the Student class cannot access the name and age fields of the Person class :

class Person {
    private String name;
   
private int age;
}

class Student extends Person {
    public String hello() {
       
return "Hello, " + name; // Compilation error: Cannot access the name field
    }
}

This makes the role of inheritance weakened. 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;
}

class Student extends Person {
    public String hello() {
       
return "Hello, " + name; // OK!
    }
}

Therefore, the protected keyword can control the access permissions of fields and methods within the inheritance tree. A protected field and method can be accessed by its subclasses and subclasses of the subclass. We will explain in detail later.

2. The use of super

The super keyword represents the parent class (super class). When the subclass refers to the field of the parent class, super.fieldName can be used . E.g:

class Student extends Person {
    public String hello() {
       
return "Hello, " + super.name;

    }
}

 

 

 

The execution of the above code will cause compilation errors, the student construction method, and the Person construction method cannot be called.

Analysis: Any class construction method must first construct the parent class construction method. If the construction method of the parent class is not explicitly called, the compiler will automatically add a super() for us, so the construction method of the Student class is actually like this

 

Then the problem is that the parent class, the Person class, does not have a default constructor, and the subclass, the Student, must display the constructor after calling the overload, that is

 

The writing in the Student class is

uploading.4e448015.gifUploading... re-upload canceled

 

Summary: If the parent class does not have a default construction method, the subclass must explicitly call super() and give the parameters so that the compiler can locate a suitable construction method. At the same time, the subclass will not inherit any construction methods of the parent class. The default construction method of the subclass is automatically generated by the compiler, not inherited

 

 

Guess you like

Origin blog.csdn.net/zl1107604962/article/details/105439625