java关键字super和this的区别

  1. 属性的区别:this访问本类中的属性,如果本类没有此属性则从父类中继续查找。super访问父类中的属性。

  2. 方法的区别:this访问本类中的方法,如果本类没有此方法则从父类中继续查找。super访问父类中的方法。

  3. 构造的区别:this调用本类构造,必须放在构造方法的首行。super调用父类构造,必须放在子类构造方法首行。

  • 1)在对拥有父类的子类进行初始化时,父类的构造方法优于子类构造函数执行;因为每一个子类的构造函数中的第一行都有一条默认的隐式语句super();
  • 2)this() 和super()都只能写在构造函数的第一行,所以this() 和super() 不能存在于同一个构造函数中;
  • 3)this和super不能用于static修饰的变量,方法,代码块;因为static修饰的成员变量,方法是属于类本身而不属于该类的实例,该方法的调用可能属于一个类,而不是对象,因而失去了意义;`package test1;
public class T1 {
	private int number;
	private String username;
	private String password;
	private int x = 100;
	public T1(int n) {
		number = n; // 这个还可以写为: this.number=n;
	}


	public T1(int i, String username, String password) {
		// 成员变量和参数同名,成员变量被屏蔽,用"this.成员变量"的方式访问成员变量.
		this.username = username;
		this.password = password;
	}

	// 默认不带参数的构造方法
	public T1() {
		this(0, "未知", "空"); // 通过this调用另一个构造方法
	}

	public T1(String name) {
		this(1, name, "空"); // 通过this调用另一个构造方法
	}

	public static void main(String args[]) {
		T1 t1 = new T1();
		T1 t2 = new T1("游客");
		t1.outinfo(t1);
		t2.outinfo(t2);
	}

	private void outinfo(T1 t) {
		System.out.println("-----------");
		System.out.println(t.number);
		System.out.println(t.username);
		System.out.println(t.password);
		f(); // 这个可以写为: this.f();
	}

	private void f() {
		// 局部变量与成员变量同名,成员变量被屏蔽,用"this.成员变量"的方式访问成员变量.
		int x;
		x = this.x++;
		System.out.println(x);
		System.out.println(this.x);
	}

	// 返回当前实例的引用
	private T1 getSelf() {
		return this;
	}

}

运行结果在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_40896997/article/details/89146281