8
A
回答
26
这意味着,假设你有:
Object x = "hello";
的类型变量的是Object
,但对象的类型,它指的是String
。它的变量类型,它确定你虽然可以做什么 - 所以你不能叫
// Invalid
String y = x.toUpperCase();
编译器只知道你调用上Object
的方法,其中不包括toUpperCase
。同样,重载方法只解决了对你了解的:
public class Superclass
{
public void foo(Object x) {}
}
public class Subclass extends Superclass
{
public void foo(String y) {}
}
...
Subclass x = new Subclass();
Superclass y = x;
x.foo("hello"); // Calls Subclass.foo(String)
y.foo("hello"); // Calls Superclass.foo(Object)
-1
public class Base
{
public object BaseMethod()
{
return new String("From Base");
}
}
public class Child extends Base
{
public object BaseMethod
{
return new String("From Child.BaseMethod (overridden)");
}
public object ChildMethod
{
return new String("From Child.ChildMethod");
}
}
public class Test
{
public static void main(String[] args)
{
Base base = new ChildMethod();
System.out.println(base.BaseMethod()); //prints "From Child.BaseMethod (overridden)"
System.out.println(base.ChildMethod()); //Will not compile as ChildMethod as reference is of type Base, and ChildMethod is not specified.
Child child = (Child) base; //But I can cast it.
System.out.println(child.ChildMethod()); // This will work.
}
}
+3
为什么downvote? – 2010-03-23 18:27:35
2
在Java base
类类型的参考可以指child
类的对象。但是使用这样的参考,我们只能访问继承到child
类的base
类的成员,而不能访问child
类可能已添加的成员。
1
如果你有一个类Foo
与公共领域foo
,并与公共领域bar
类Bar extends Foo
...
- 即使对象实际上是
Bar
,Foo myRef = new Bar();
也只会允许您访问myRef.foo
。 Bar myRef = new Bar();
允许访问myRef.foo
和myRef.bar
。因为该参考声明为Bar
。
5
例如:
Bike b = new Bike();
Bike b2 = new MountainBke();
b.speedUp();
b2.speedUp();
b2.shiftGearUp();
在上面的例子中,假设自行车不具有shiftUp
方法。行b2.shiftGearUp()
不会编译,因为JVM只知道b2
是Bike
而不是MountainBike
。
你可以把它用它铸造于山地自行车工种:
((MountainBike)b2).shiftGearUp(); // This compiles and runs propperly
0
“明白它 是引用变量的类型是很重要的 - 没有对象的类型它将 指向 - 确定哪些成员可以访问 。“
这意思是,编译器检查类的方法和其他成员的存在参考变量的,例如,假设你有一个Dog
子类,其延伸Animal
基类,
Animal obj=new Dog();
obj.makeSound();
这里编译器检查在动物类makeSound()方法是否申报或不为它编写。
相关问题
- 1. 爪哇,多类实例变量参考
- 2. 爪哇 - 听变量变化
- 3. 爪哇 - 对象池相同的参考
- 4. 爪哇复制阵列 - 参考
- 5. 痛饮 - 爪哇 - 通过参考INT
- 6. 作为可变通用参数 - 爪哇
- 7. 爪哇 - 设置环境变量
- 8. 爪哇 - 外部变量声明
- 9. 爪哇 - volatile变量没有更新
- 10. 爪哇 - 映射流变量再分配
- 11. 爪哇不接受环境变量
- 12. 爪哇 - 在
- 13. 爪哇 - 从另一个类使用变量,方法参数
- 14. 爪哇 - 在方法参数
- 15. 爪哇这个参数
- 16. 爪哇 - 参数标注
- 17. 爪哇 - 继承
- 18. 爪哇 - 改变阵列
- 19. 爪哇 - 转变INT枚举
- 20. 爪哇 - 循环由数量
- 21. 爪哇 - 的ArrayList
- 22. 爪哇:enum toString()
- 23. 爪哇:使用一个枚举作为数组参考
- 24. 爪哇构造:参考MyCalendarItem是不明确的
- 25. 设置变量引用另一个变量,爪哇
- 26. 爪哇 - 每行
- 27. 爪哇从
- 28. 逆阵列(爪哇)// Invertir阵列(爪哇)
- 29. 爪哇 - 在Mac
- 30. 爪哇JRadioButton
哪里是取自这句话? – 2010-03-23 14:16:27
很抱歉,但我完全不记得...... 让我知道,如果我不允许根据某些网站上发布的报价提问。 – 2010-03-23 14:20:06
顺便说一句,该报价不显示在Google搜索...除了此页面。要么你输入错了,要么你从某个没有被Google索引的网站上获得它!?! – 2010-03-23 14:35:03