Introduction to super keyword in Java

Since the subclass cannot inherit the construction method of the parent class, if you want to call the construction method of the parent class, you can use the super keyword. super can be used to access the constructor, common methods and properties of the parent class.

The function of the super keyword:

  • Explicitly call the parent class constructor in the subclass constructor
  • Access member methods and variables of the parent class.

1. Use super to call the construction method of the parent class

super must be the first statement in the subclass construction method

When we define multiple constructors in the parent class, we should include a constructor without parameters to prevent errors when the subclass omits super .

Declare the parent class Person and subclass Student, and define a constructor with parameters in the Person class. The code is as follows:

public class Person {
    public Person(String name) {

    }
}
public class Student extends Person {

}

You will find that the Student class has a compilation error, prompting you must explicitly define the construction method, the error message is as follows:

Implicit super constructor Person() is undefined for default constructor. Must define an explicit constructor

In this example, the JVM adds a no-argument constructor to the Student class by default, and super() is called by default in this method, but the constructor does not exist in the Person class, so compilation errors will occur.

If no constructor is written in a class, JVM will generate a default no-argument constructor. In the inheritance relationship, because in the construction method of the subclass, the first statement defaults to calling the parameterless construction method of the parent class (that is, the default is super(), generally this line of code is omitted). So when a parameterized constructor is defined in the parent class, but no parameterless constructor is not defined, the compiler will force us to define a constructor with the same parameter type. 

The subclass Student inherits the Person class and uses the super statement to define the construction method of the Student class. The sample code is as follows:

public class Student extends Person {
    public Student(String name, int age, String birth) {
        super(name, age); // 调用父类中含有2个参数的构造方法
    }

    public Student(String name, int age, String sex, String birth) {
        super(name, age, sex); // 调用父类中含有3个参数的构造方法
    }
}

 As can be seen from the above Student class construction method code, super can be used to directly call the construction method in the parent class, which makes writing code more concise and convenient.
The compiler will automatically add super();to the first sentence of the subclass construction method to call the parent class's no-parameter construction method. It must be written in the first sentence of the subclass construction method, or it can be omitted. When calling other construction methods of the parent class through super, you only need to pass the corresponding parameters.

public class Student 
{
	int number;
	String name;
	Student(){
	}
	Student(int number, String name){
		this.number = number;
		this.name = name;
	}
	public int getNumber(){
		return number;
	}
	public String getName(){
		return name;
	}
}
public class UniverStudent extends Student
{
	boolean isMarriage;   //子类新增的结婚属性
	UniverStudent(int number, String name, boolean b){
		super(number, name);
	}
	public boolean getIsMarriage(){
		return isMarriage;
	}
}
public class Example5_6 
{
	public static void main(String[] args) 
	{
		UniverStudent zhang = new UniverStudent(20111, "张三", false);
		int number = zhang.getNumber();
		String name = zhang.getName();
		boolean marriage = zhang.getIsMarriage();
		System.out.println(name + "的学号是:" + number);
		if(marriage == true){
			System.out.println(name + "已婚");
		}
		else{
			System.out.println(name + "未婚");
		}
	}
}

2. Call the hidden member variables and methods

Using super to access members in the parent class is similar to the use of this keyword, except that it refers to the parent class of the subclass. The syntax format is as follows:

super.member

Among them, member is an attribute or method in the parent class. Use super to access the properties and methods of the parent class without being in the first line.

If you want to use member variables or methods hidden by the subclass, you can use the keyword super . For example, super.x , super.play () are to access and call the member variable x hidden by the subclass and the method play() .

When super calls a hidden method, the member variable that appears in the method refers to the hidden member variable

public class Sum 
{
	int n;
	public double f(){
		double sum = 0;
		for(int i = 1; i<= n; i++){
			sum += i;
		}
		return sum;
	}
}
public class Average extends Sum 
{
	double n;  //子类继承的int型变量n被隐藏
	public double f(){
		double c;
		super.n = (int)n;  //double类型变量n做int转换,将结果赋给隐藏的int型变量n
		c = super.f();
		return c + n;
	}
	public double g(){
		double c;
		c = super.f();
		return c - n;
	}
}
public class Example5_7 
{
	public static void main(String[] args) 
	{
		Average aver = new Average();
		aver.n = 100.5678;
		double result1 = aver.f();
		double result2 = aver.g();
		System.out.println("result1 = " + result1);
		System.out.println("result2 = " + result2);
	}
}

If rewritten as (reverse order)

double result2 = aver.g();

double result1 = aver.f();

operation result:

result1 = 5150.5678

result2 = -100.5678

Because "super.f();" needs to be executed during the execution of "aver.g();", the n that appears in super.f() is hidden and n has not yet been assigned. The default is 0;

3. The difference between super and this

this refers to the reference of the current object, and super is the reference to the parent object of the current object. Let's briefly introduce the usage of super and this keywords.

Usage of the super keyword:

  • super. Parent property name: call the property in the parent class
  • super. Parent method name: call the method in the parent class
  • super(): call the parameterless construction method of the parent class
  • super (parameter): call the parameterized construction method of the parent class

If the first line of code of the constructor is not this() and super(), the system will add super() by default.


Usage of this keyword:

  • this. Property name: Represents the property of the current object
  • this. method name (parameter): Indicates the method of calling the current object

When local variables and member variables conflict, use them this.to distinguish them.

About  Java  similarities and differences between this and super keywords, can be briefly summarized in the following items.

  1. When the variable or method name in the subclass and the parent class is the same, use the super keyword to access. It can be understood that super is a pointer to an object of its own parent. Call the construction method of the parent class in the subclass.
  2. this is an object of itself, representing the object itself, which can be understood as this is a pointer to the object itself. Call other methods in the same class.
  3. This and super cannot appear in the same construction method at the same time, because this will inevitably call other construction methods, and there will definitely be super statements in other construction methods, so if there are the same statements in the same construction method, it will be lost The meaning of the statement, the compiler will not pass.
  4. Both this() and super() refer to objects, so neither can be used in a static environment, including static variables, static methods, and static statement blocks.
  5. Essentially, this is a pointer to the object itself, but super is a Java keyword.

The name attribute of public type and the name attribute of private type are defined in the Animal class and the Cat class, respectively, and the Cat class inherits the Animal class. Then, we can use the super keyword in the Cat class to access the name attribute in the parent class Animal, and the this keyword to access the name attribute in this class, as shown in the following code:

// 父类Animal的定义
public class Animal {
    public String name; // 动物名字
}

//子类Cat的定义
public class Cat extends Animal {
    private String name; // 名字

    public Cat(String aname, String dname) {
        super.name = aname; // 通过super关键字来访问父类中的name属性
        this.name = dname; // 通过this关键字来访问本类中的name属性
    }

    public String toString() {
        return "我是" + super.name + ",我的名字叫" + this.name;
    }

    public static void main(String[] args) {
        Animal cat = new Cat("动物", "喵星人");
        System.out.println(cat);
    }
}
我是动物,我的名字叫喵星人

Guess you like

Origin blog.csdn.net/qq_43629083/article/details/108673552