4

我知道在创建这样的新对象时:

GeomObject tri = new Triangle();

更通用并且允许更多的可重复性,但是当 tri 像这样创建时会发生什么:

Triangle tri = new Triangle();

既然 Triangle 是 GeomObject 的子类,那么 tri 不还是 GeomObject 吗?声明的类型如何影响编译?谢谢

*添加:另一个问题:说我有

Integer n1 = new Integer(3);
Object n2 = new Integer(4); 
System.out.println(n1.compareTo(n2));

我在 Eclipse 上试过这个,即使我用 n2 颠倒了 n1,我也得到了错误。我认为 n2.compareTo(n1) 会起作用,因为它会调用 Object compareTo 方法,并且由于 Integer 是对象的实例,所以它是可以通过的,但事实并非如此。你能解释一下吗?

4

1 回答 1

11

既然Triangle是 的子类GeomObject,那还不triGeomObject吗?

是的。使用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直接使用,至少你了解你真正在做什么。
于 2013-09-12T22:04:48.097 回答