public class Father {}
class Child extends Father {}
static void f1(Father f){}
static void f2(Child c){}
Child x=new Child();
Father y=new Father();
Father z=new Child();
f1(x);
f1(y);
f1(z);
f2(x);
f2(y);
f2(z); //能执行吗? 输出什么?错在哪里?
class Child extends Father {}
static void f1(Father f){}
static void f2(Child c){}
Child x=new Child();
Father y=new Father();
Father z=new Child();
f1(x);
f1(y);
f1(z);
f2(x);
f2(y);
f2(z); //能执行吗? 输出什么?错在哪里?
f2(z);
这两个不行;如果f2((Child)z)这样就行了,
Father z=new Child(); 这种情况父类可以Cast成子类。
像f2((Child)y)就不行了。
(1)class Child extends Father {
public static void main(String args[]) {
Child x=new Child();
Father y=new Father();
Father z=new Child();
f1(x);
f1(y);
f1(z);
f2(x);
f2(y);
f2(z); //能执行吗? 输出什么?错在哪里?
} private static void f2(Father z) {
// TODO Auto-generated method stub
} private static void f1(Father y) {
// TODO Auto-generated method stub
} private static void f2(Child x) {
// TODO Auto-generated method stub
}
}
以上为正确编译。(2)class Child extends Father {
public static void main(String args[]) {
Child x=new Child();
Father y=new Father();
Father z=new Child();
f1(x);
f1(y);
f1(z);
f2(x);
f2((Child)y);
f2((Child)z); //能执行吗? 输出什么?错在哪里?
}
private static void f1(Father y) {
// TODO Auto-generated method stub
} private static void f2(Child x) {
// TODO Auto-generated method stub
}
}
以上是编译没有错误,但是运行出错的代码。
(3)class Child extends Father {
public static void main(String args[]) {
Child x=new Child();
Father y=new Father();
Father z=new Child();
f1(x);
f1(y);
f1(z);
f2(x);
f2(y);
f2((Child)z); //能执行吗? 输出什么?错在哪里?
} private static void f2(Father z) {
// TODO Auto-generated method stub
} private static void f1(Father y) {
// TODO Auto-generated method stub
} private static void f2(Child x) {
// TODO Auto-generated method stub
}
}
这样做,编译运行都没有错误了,搞定!
楼主处理要写在类里,还有缺少主方法 class Father {
}
class Child extends Father {
}public class Test{
static void f1(Father f){System.out.println("static void f1(Father f)");}
static void f2(Child c){System.out.println("static void f2(Child c)");};
public static void main(String[] args){
Child x=new Child();
Father y=new Father();
Father z=new Child();
f1(x);
f1(y);
f1(z);
f2(x);
//f2(y);有错,子类引用指向父类
//f2(z);有错,子类引用指向父类
}
}