码迷,mamicode.com
首页 > 其他好文 > 详细

两段关于this的代码

时间:2018-10-13 00:03:19      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:vat   new   stat   end   str   []   运行   并且   属性   

/*
* 子类未重写父类方法,通过子类对象调用父类方法,父类方法中的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方法运行");

}
}

两段关于this的代码

标签:vat   new   stat   end   str   []   运行   并且   属性   

原文地址:https://www.cnblogs.com/-lyw/p/9780698.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!