类Apple是Fruit的子类,类Pear是Fruit的子类
Apple a=new Apple();
Fruit f=a;
Pear p=new Pear();
请问:Fruit f=a这句是把Apple型看成Fruit型,那为什么比较Apple与Pear型引用
if(a==p)
时会出错
Apple a=new Apple();
Fruit f=a;
Pear p=new Pear();
请问:Fruit f=a这句是把Apple型看成Fruit型,那为什么比较Apple与Pear型引用
if(a==p)
时会出错
类Apple是Object的子类,类Pear是Object的子类
Apple a=new Apple();
Object f=a;
Pear p=new Pear();
请问:Object f=a这句是把Apple型看成Object型,那为什么比较Apple与Pear型引用
if(a==p)
时会出错==================
可以看出 Apple 与 Pear 没啥关系, 编译器就知道 a与p比较没啥意义
就好像有这么一句代码:
int j=5;
String k="nihao";
if(j==k){}//这句会出错
所以如果把Apple和Pear分别看成一种数据类型,那么比较它们的对象的话就会出现数据类型不相容的错误
,如果只是想比较它们的内存地址的话,我觉得用toString()应该可以,呵呵
package action;class Fruit {
}class Apple extends Fruit {
}class Pear extends Fruit {
}public class Test { public static void main(String[] args) {
Apple apple = new Apple();
Pear pear = new Pear();
Fruit f = apple;
if (f == pear) {
System.out.println(true);
} else
System.out.println(false);
}
}//output: false
apple和 pear 是两个不相关的类,
Fruit f = apple;后,父类引用指向子类,编译器明白这个..至于apple和pear.两个完全不同的类 ,比较没有意义。直接false
两者并无直接关系,所以比较不了。