Java中的this與super關鍵字

Java中的this與super關鍵字
this關鍵字
1.this是啥子?
this代表當前類的對象
2.this能用在那些地方
1.可以用在成員方法中(訪問當前對象的屬性,調用當前對象的方法)
2.可以用在構造方法中(this必須放在第一行)
3.在成員方法中,不引起歧義的時候this可以省略

public class ThisTest {
public static void main(String[] args) {
People tang = new People(“糖糖”);
System.out.println(tang.getName());//糖糖
tang.eat();
People jian = new People(“尖尖”);
jian.eat();
People zhong = new People();
zhong.eat();
}
}

新建一個people類
public class People {
private String name;
private int age;
public People(){}
public People(String _name){//_name只是爲了區分而已
this();
name = _name;
}
public People(int age){
this.age = age;//this不可以省略
}
public void eat(){
System.out.println(name+“在大喫特喫”);//this可以省略
System.out.println(this.getName());
}
public String getName(){
return name;
}
}

效果如下圖
在這裏插入圖片描述

最後輸出null和null在大喫特喫的原因是在ThisTest類中
People zhong = new People();//沒有輸入代表爲null

java 中的super關鍵字
this:代表的是當前類的對象
super:代表的是當前類的父類的對象(建立在繼承的基礎上)

1.super用在成員方法中
2.super用在構造方法中

super在構造方法中使用時必須位於第一行
super和this表示構造方法的時候不能共同使用

子類構造方法中必須調用父類的構造方法
如果未顯示,則默認調用父類無參構造
如果顯示,則super必須位於第一行
如果未顯示而父類沒有無參構造則程序報錯

public class Super {
public static void main(String[] args) {

	Dog dog = new Dog();
	dog.eat();
	
}	

}
新建一個動物(Animal)類
public class Animal {
String name;

public Animal(){//父類的無參構造
	System.out.println("Animal類的無參構造");
}

public Animal(String name){//父類的無參構造
	this.name = name;
}

public void eat(){
	System.out.println("Animal喫的方法");
}

}

再新建一個狗(Dog)類,繼承動物(Animal)類
public class Dog extends Animal{
String name;

public Dog(){
	super("123");
	System.out.println("Dog類的無參構造");
}

public Dog(String name){
	super(name);//調用本類的無參構造
	this.name = name;
	//this();
	//super.eat();//這樣寫是可以的
}

public void eat(){
	super.eat();//調用父類的eat方法
	//this.eat();//調用自己的eat方法
	System.out.println(super.name+"Dog喫的方法");
}

}

輸出結果爲下圖
在這裏插入圖片描述

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