两段关于this的代码

/*
* 子类未重写父类方法,通过子类对象调用父类方法,父类方法中的this指向父类对象。
*/
public class 关于this的使用1 {

public static void main(String[] args) {
Cat cat = new Cat("橘猫");
System.out.println(cat.getName());
}
}

class Animal{
private String name;

public String getName() {
return this.name; //父类中的方法不能访问子类对象中的属性,并且this指向的也是父类对象
}
}

class Cat extends Animal{
private String name;

public Cat(String name) {
this.name = name;
}

public Cat() { }
}

---------------------------------------------------------------------------

/*
* 子类重写了父类方法之一,通过子类对象调用未重写的父类方法,此父类方法中调用被重写的方法,
* this指向子类对象。
*/

public class 关于this的使用2 {

public static void main(String[] args) {

//People Chinese = new Chinese();
Chinese chinese = new Chinese();
chinese.a();

}

}

class People{

public void a() {
System.out.println("People中的a方法运行");
this.b(); //子类重写了b方法,this指向子类对象
}
public void b() {
System.out.println("People中的b方法运行");
}
}

class Chinese extends People{

public void b() {
System.out.println("Chinese中的b方法运行");

}
}

猜你喜欢

转载自www.cnblogs.com/-lyw/p/9780698.html