既然Triangle是 的子类GeomObject,那还不tri是GeomObject吗?
是的。使用instanceof运算符对此进行测试:
System.out.println( (tri instanceof Triangl) ); //prints true
System.out.println( (tri instanceof GeomObject) ); //prints true
System.out.println( (tri instanceof Object) ); //prints true because every class extends from Object
声明的类型如何影响编译?
它不会影响任何事情,只会使您的代码不灵活,以防您需要使用GeomObject不是Triangle.
更多信息:
我认为这n2.compareTo(n1)会起作用,因为它会调用Object#compareTo方法
这是不正确的,因为Object类没有compareTo方法。
另一方面,由于您在接收另一种类类型时将 an 传递给该方法,n1.compareTo(n2)因此将不起作用。ObjectcompareToInteger#compareToInteger
请注意,在声明此内容时:
Object n2 = new Integer(4);
- 变量类型将是
Object,无论您将其初始化为Integer还是其他类,例如String。
- 只有被覆盖的方法的行为与对象引用运行时类型中定义的一样,这意味着如果你的变量
n2包含一个本身将表现为. 在类的情况下,这些方法是和。IntegerIntegerObjectIntegerObjectIntegerequalshashCodetoString
- 上面提供的链接:“编程到接口”是什么意思?解释了使用接口(或抽象类或泛型类)通过泛型接口/类而不是直接实现来概括工作的好处。请注意,在某些情况下,这种方法将不适用,例如您当前的示例使用
Objectwhen you should use Integer。请注意,Object类太通用了(至少在这种情况下),所以我不建议Object直接使用,至少你了解你真正在做什么。