class a{
int length;
public a(int length){
this.length = length;
}
public String toString() {
return "calling a!";
}
}class b extends a{
a width;
public b(int length,int width){
super(length);
this.width=new a(width);
}
public a getlength() {
return this;
} public a getWidth() {
return width;
} public String toString() {
return "calling b!";
}
}class c{
public static void main(String arg[]) {
b line_1=new b(1,5);
a t=line_1.getlength();
System.out.println(line_1.getlength());
System.out.println(t);
}
}为什么上面程序打印出来是 calling b!
calling b!
为什么两个都是calling b!啊 getlength() 中是return的都是a类的啊,那里的return this到底是什么意思啊?
int length;
public a(int length){
this.length = length;
}
public String toString() {
return "calling a!";
}
}class b extends a{
a width;
public b(int length,int width){
super(length);
this.width=new a(width);
}
public a getlength() {
return this;
} public a getWidth() {
return width;
} public String toString() {
return "calling b!";
}
}class c{
public static void main(String arg[]) {
b line_1=new b(1,5);
a t=line_1.getlength();
System.out.println(line_1.getlength());
System.out.println(t);
}
}为什么上面程序打印出来是 calling b!
calling b!
为什么两个都是calling b!啊 getlength() 中是return的都是a类的啊,那里的return this到底是什么意思啊?
在 class b里面的this指的当然是b的对象return的类型a,但其实this 是b这有点像多态吧, a是父类,b是子类
可以用父类的 对象名指向子类,但父类的对象名所指的内容到底是什么,必须要运行时才决定,可能是 a的对象,可能是b的对象
那到底是什么决定的啊?
还有就是a t=line_1.getlength(); 这句决定了t一定是a类的吧```
为什么打印t还是calling b呢?
a t=line_1.getlength();t不一定是a,有可能是a,或a的子类
这样比较好理解,你可以定义动物 t = 动物1;
动物 t = 大象1;
动物 t = 狮子1;t不一定非要是动物对象,可以是大象,因为大象也是动物,可以是狮子,因为狮子也是动物
return this;
}
也就是说这里return this 最后返回的就是b类的
然后把这个值不管赋给a类或者b类的变量 最后那个变量都是b类的?
是不是这里理解的? :
return this 是返回(上转给)一个父类a的变量, 然后a t=line_1.getlength(); 也是一样的道理上转给一个父类a的变量t
但是这些上转的对象都有了子类的方法 所以都使用子类的toString 而不使用父类的toString这样理解对嘛?
public String toString() {
return "calling b!";
}
2.父类对象接收父类或子类对象
a t=line_1.getlength(); //getlength()中return this,this只待b类对象
3.JVW会根据实际创建的对象调用相应的方法
System.out.println(t); //实际创建的是b类对象,因此调用重写的toString()
1,你的b是a的子类,在java里面有个特点就是,如果子类有的方法就不去调用父类的了,这叫做重写
2,a是b的父类,那么如果有一个方法需要类a的话,你传进入各类b,jvm认为这是可以的,但是反之则不可以
3,this这个关键字是只类的本身。
http://zhidao.baidu.com/question/21122060.html