Distinguish between this reference and super keyword in Java, distinguish between method rewriting and method overloading


foreword

This article mainly introduces the this keyword and the super keyword in Java, and distinguishes method overloading and method rewriting in Java.


1. This reference

1. Why is there a this reference

Let's look at an example first:

public class Date {
    
    
	 public int year;  //为了简单起见,只定义了年。
	 public void setDay(int y){
    
    
		 year = y;
	 }
	 public void printDate(){
    
      //打印年份
		 System.out.println(year);
	 }
	 public static void main(String[] args) {
    
    
		 Date d1 = new Date();
		 d1.setDay(2020);//设置年份
		 // 打印内容
		 d1.printDate();
	 }
}

The result is as follows:
insert image description here
If the above example is slightly changed:

public class Date {
    
    
	 public int year;  //为了简单起见,只定义了年。
	 public void setDay(int year){
    
    
		 year = year;
	 }
	 public void printDate(){
    
      //打印年份
		 System.out.println(year);
	 }
	 public static void main(String[] args) {
    
    
		 Date d1 = new Date();
		 d1.setDay(2020);//设置年份
		 // 打印内容
		 d1.printDate();
	 }
}

The result is as follows:
insert image description here

In order to solve the problem of the above example, we introduce this reference

2. What is this reference

The java compiler adds a hidden reference type parameter to each "member method" . The reference parameter points to the current object (the object that calls the member method when the member method is running), and the operation of all member variables in the member method is Access through this reference.

Improve the above code:

public class Date {
    
    
	 public int year;  //为了简单起见,只定义了年。
	 public void setDay(int year){
    
    
		 this.year = year;
	 }
	 public void printDate(){
    
      //打印年份
		 System.out.println(year);
	 }
	 public static void main(String[] args) {
    
    
		 Date d1 = new Date();
		 d1.setDay(2020);//设置年份
		 // 打印内容
		 d1.printDate();
	 }
}

The result is as follows:
insert image description here

3. The characteristics of this reference

① The type of this: the corresponding class type reference, that is, which object is called is the reference type of that object.
② this can only be used in "member methods".
③ In the "member method", this can only refer to the current object, and can no longer refer to other objects, and has the final attribute.
④ this is the first hidden parameter of the "member method", and the compiler will automatically pass it. When the member method is executed, the compiler will be responsible for passing the reference of the calling member method object to the member method, and this is responsible for receiving it.


Two, the super keyword

1. Why is there a super keyword?

When members with the same name may exist in the subclass and the parent class, what should I do if I want to access the members with the same name in the parent class in the method of the subclass?

Java provides the super keyword, its main function: to access the members of the parent class in the method of the subclass.

2. Specific example analysis

example:

//父类
public class Animal{
    
     
	int a; 
	int b; 
	public void methodA(){
    
     
		System.out.	println("Animal中的methodA()");
    }
}
//子类继承了父类
public class dog extends Animal{
    
     
	int a; // 与父类中成员变量同名且类型相同 
	char b; // 与父类中成员变量同名但类型不同 
	public void methodA() {
    
     
		System.out.	println("dog中的methodA()方法"); 
   } 
   public void methodB(){
    
     
	// 对于同名的成员变量,直接访问时,访问的都是子类的 
	a = 10; // 等价于: this.a = 10; 
	b = 20; // 等价于: this.b = 20; 
	// 注意:this是当前对象的引用 
	// 访问父类的成员变量时,需要借助super关键字 
	// super是获取到子类对象中从基类继承下来的部分 
	super.a = 20; 
	super.b = 30; 
	// 如果在子类中要访问重写的基类方法,则需要借助super关键字 
	methodA(); // 直接访问,则永远访问到的都是子类中的methodA(),基类的无法访问到 
	super.methodA(); // 访问基类的methodA() 
	} 
} 


3. Comparison of this and super

1. Similarities

① are keywords in Java. ② It can only be used in non-static methods
of the class to access non-static member methods and fields. ③ When called in the construction method, it must be the first statement in the construction method , and cannot exist at the same time.

2. Differences

① this is the reference of the current object , which is the object calling the instance method; super is equivalent to the reference of some members inherited from the parent class in the subclass object .
② In non-static member methods, this is used to access the methods and properties of this class, and super is used to access the methods and properties inherited from the parent class.
③ this is a hidden parameter of the non-static member method, super is not a hidden parameter.
④ When directly accessing the members of this class in the member method, this will be restored after compilation , that is, the non-static members of this class are all accessed through this; Super does not exist at the code level
⑤ In the construction method: this() is used to call the construction method of this class, and super() is used to call the parent class construction method. The two calls cannot appear in the construction method at the same time .
⑥ There must be a super() call in the construction method, and the compiler will increase if the user does not write it, but this() will not exist if the user does not write it.

example:

//父类
public class Animal{
    
     
	int a; 
	int b; 
	public void methodA(){
    
     
		System.out.	println("Animal中的methodA()");
    }
}
//子类继承了父类
public class dog extends Animal{
    
     
	public void methodA() {
    
     
	//内容不同,重写了父类中的methodA()方法
		System.out.	println("dog中的methodA()方法"); 
   } 
}

4. Method rewriting

Rewrite (override): Also called coverage.

It is the subclass rewriting the non-static, non-private modification, non-final modification, non-construction method and other methods of the parent class , and the return value and formal parameters cannot be changed . That is, only the inside of the method body ({...}) can be changed.

Note:
① When a subclass rewrites the method of the parent class, it must generally be consistent with the prototype of the parent class method : the modifier return value type method name (parameter list) must be exactly the same. ② After JDK7, the return value type of
the rewritten method can be different , but it must have a parent-child relationship, that is, the child access cannot have lower access rights than the rewritten method in the parent class. For example, if the method of the parent class is modified by public, the method cannot be declared as protected if the method is rewritten in the subclass. ③ The methods and construction methods of the parent class modified by static and private cannot be rewritten. ④ The subclass and the parent class are in the same package, except for private and final methods. All other methods can be overridden. ⑤ If the subclass and parent class are not in the same package, then the subclass can only rewrite the non-final methods declared public and protected of the parent class . ⑥ The overridden method can be explicitly specified using the @Override annotation. This annotation can perform some legality checks.




5. Method overloading

Overloading: multiple methods with the same name but different parameter lists.

Note:
①The method names must be the same .
② The parameter lists must be different ( the number of parameters is different , the type of parameters is different , and the order of types is different, and only one of the three needs to be satisfied) .
③ It has nothing to do with whether the return value type is the same.

Example: The following three methods constitute overloading

//方法1:
 public static int add(int x, int y) {
    
    
 return x + y; 
 }
//方法2:
 public static double add(double x, double y) {
    
    
 return x + y;
 }
 //方法3:
 public static double add(double x, double y, double z) {
    
    
 return x + y + z;
 }

6. The difference between rewriting and overloading

insert image description here


Summarize

That's all for this article.

Guess you like

Origin blog.csdn.net/m0_53689542/article/details/124577683