父类
[code="java"]
package test;
public class Car {
public void car(Other o){
System.out.println(this);
o.process(this);
}
}
[/code]
子类
[code="java"]
package test;
public class Audi extends Car{
}
[/code]
这个类里面有两个重载的方法,参数分别为父类和子类
[code="java"]package test;
public class Other {
public void process(Audi a){
System.out.println("Audi");
}
public void process(Car c){
System.out.println("Car");
}
}[/code]
测试类:
[code="java"]
package test;
public class Test {
public static void main(String[] args) {
Other o = new Other();
Car c = new Car();
c.car(o);
Audi a = new Audi();
a.car(o);
}
}
[/code]
this代表的是调用该方法的当前对象,当我用Audi的对象调用car方法时,this指代的是Audi对象,执行o.process(this);方法是应该是执行的Other
类里面的
public void process(Audi a){
System.out.println("Audi");
}
才对,为什么两次打印的都是Car呢,我很疑惑
如何你把Audi改成如下就可以达到你的要求:
[code="java"]public class Audi extends Car {
@Override
public void car(Other o) {
System.out.println(this);
o.process(this);
}
}[/code]
而之所以你现在的代码输出Car,是因为子类中的car方法,默认是这样的:
[code="java"] @Override
public void car(Other o) {
// TODO Auto-generated method stub
super.car(o);
}[/code]
也就是说调用的还是父类的对象,也就car方法里的this指代的是父类
你的Audi没有重写该方法。
所有在运行时都会调用父类Car的该方法。
没一个子类的构造方法调用的时候,都会去调用父类的构造方法。
那么你父类里的this当然指的是父类自身的对象。
你的Audi没有重写该方法。
所有在运行时都会调用父类Car的该方法。
在进行方法调用的时候,会默认传入该方法所属实例(也就是this)作为方法内的变量,这里的car方法属于Audi的父类Car的方法,故 a.car(o);实际上调用的是super.car(o).
这应该是方法参数的匹配问题
你可以尝试去掉Other里面的
public void process(Car c){
System.out.println("Car");
}
你会发现
o.process(this);
报The method process() in the type Other is not applicable for the arguments
这是因为在Car里面,方法process(this)的this的类型是Car