[Java keywords] super contrast this

super (call parent class)

super is mainly to call the parent class

Create test file

ThisAndSuper.class

package test;
public class ThisAndSuper {
	public static void main(String[] args) {
		City c = new City();
		c.value();
	}
}

Country.class

package test;
class Country {
    String name;
    void value() {
       name = "China";
    }
}

City.class

package test;
class City extends Country {
	String name;
	void value() {
		name = "GuangZhou";
		super.value(); // 调用父类的方法
		System.out.println(this.name);
		System.out.println(super.name);
	}
}

Commissioning notes (execution steps)

Insert picture description here

  1. Enter class city and assign name = "GuangZhou";
  2. Run to super.value (); call the method of the parent class, assign name = "China";
  3. At this point, the City instance contains two names.

Results of the

GuangZhou
China

this (call current)

this is mainly to call the current class

Create test file

package test;
public class ThisAndSuper {
	public static void main(String[] args) {
		Person Harry = new Person();
		System.out.println("Harry's age is " + Harry.GetAge(12));
	}
}

package test;
public  class Person {
	private int age = 10;
	public Person() {
		System.out.println("初始化年龄:" + age);
	}
	public int GetAge(int age) {
		this.age = age;
		return this.age;
	}
}

Debugging notes

Person Harry = new Person();//初始化Person时,执行System.out.println("初始化年龄:" + age);输出age值为10
System.out.println("Harry's age is " + Harry.GetAge(12));//传入参数12,赋值给age,输出age=12

Results of the

初始化年龄:10
Harry's age is 12
Published 99 original articles · Like 106 · Visit 270,000+

Guess you like

Origin blog.csdn.net/lglglgl/article/details/105040174