首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2ME开发 >

调用父类的方法中this是那个对象,该如何处理

2011-12-30 
调用父类的方法中this是那个对象public class Objec {static class Parent{private int i 0protected v

调用父类的方法中this是那个对象
public class Objec {
static class Parent{
private int i = 0;

protected void add() {
i++;
}

public void printOut() {
this.add();
System.out.println(this.i);
}
}
  class Child extends Parent{
private int i=0;
@Override
protected void add() {
 
i=i+2;
}
  }
   
public static void main(String[] args) {
Parent b=new Parent();
b.printOut();
Child a=new Objec().new Child();
a.printOut();
b=a;
b.printOut();

}

}


[解决办法]
当对象是子类对象的时候,
“this.字段”如果出现在父类代码中,指的就是父类属性。
“this.方法”不管出现在父类还是子类代码中,指的都是子类方法。
“this.字段”如果出现在子类代码中,指的就是子类属性。
[解决办法]
this是指当前对象,所以当前对象是什么类型的实例就是什么类型的对象
Parent b=new Parent();
b.printOut(); //this是Parent对象
Child a=new Objec().new Child();
a.printOut();//this是Child对象
b=a;//b指向Child对象
b.printOut(); //所以this是Child对象

热点排行