java中的super()和this

super()和this()類似,區別是,super()從子類中調用父類的構造方法,this()在同一類內調用其它方法
demo
‘’'java
//superclass
public class Person {
Person() {
System.out.println("Superclass: constrcutor without parameters ");
}

Person(String name) {
	System.out.println("Superclass: constructor with name  = " + name);
}
public void prt(String str) {
	System.out.println(str);
}

}

//subclass
public class Chinese extends Person {
Chinese() {
super();
prt(" subclass: without para");
}

Chinese(String name){
	super();
	prt("sunclass: with para1: " + name);
}

Chinese(String name, int age){
	//super();
	this(name);
	prt("subclass:with para2: " + name + age);
}

}

public class Main {

public static void main(String[] args) {
	Chinese ch = new Chinese();
	ch.prt("############################");
	ch = new Chinese("ensheng");
	ch.prt("############################");
	ch = new Chinese("enshi",23);
}

}

Result
![在這裏插入圖片描述](https://img-blog.csdnimg.cn/20191014132917638.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzM2MDk3Mzkz,size_16,color_FFFFFF,t_70)
this(name)調用了Children(string name)的構造方法,
super(name)調用了Person(string name);
改寫代碼,增加Animal類,讓person來繼承Animal
```java
public class Animal {
	Animal(){
		System.out.println("Superclass:animal");
	}
}

public class Person extends Animal {
.....
}

Result
在這裏插入圖片描述
所有父類的構造方法依次執行。

super可以理解爲是指向自己超(父)類對象的一個指針,而這個超類指的是離自己最近的一個父類。

reference
【java】this()與super()使用詳解

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章