【Java关键字】super对比this

super(调用父类)

super主要是调用父类

创建测试文件

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);
	}
}

调试注解(执行步骤)

在这里插入图片描述

  1. 进入class City,赋值name = “GuangZhou”;
  2. 运行至super.value(); 调用父类的方法,赋值name = “China”;
  3. 此时,City实例中含两个name。

执行结果

GuangZhou
China

this(调用当前)

this主要是调用当前类

创建测试文件

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;
	}
}

调试注解

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

执行结果

初始化年龄:10
Harry's age is 12
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章