2010-03-23 162 views
8

“明白 它是参考变量的类型是非常重要的 - 不对象,它指的是 的类型 - 用于确定什么成员可以 被访问”爪哇 - 参考变量

你的意思是什么? 这是限制在继承的概念吗? JVM如何处理它?

+3

哪里是取自这句话? – 2010-03-23 14:16:27

+0

很抱歉,但我完全不记得...... 让我知道,如果我不允许根据某些网站上发布的报价提问。 – 2010-03-23 14:20:06

+0

顺便说一句,该报价不显示在Google搜索...除了此页面。要么你输入错了,要么你从某个没有被Google索引的网站上获得它!?! – 2010-03-23 14:35:03

回答

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,并与公共领域barBar extends Foo ...

  • 即使对象实际上是BarFoo myRef = new Bar();也只会允许您访问myRef.foo
  • Bar myRef = new Bar();允许访问myRef.foomyRef.bar。因为该参考声明为Bar
5

例如:

Bike b = new Bike(); 
Bike b2 = new MountainBke(); 
b.speedUp(); 
b2.speedUp(); 
b2.shiftGearUp(); 

在上面的例子中,假设自行车不具有shiftUp方法。行b2.shiftGearUp()不会编译,因为JVM只知道b2Bike而不是MountainBike

你可以把它用它铸造于山地自行车工种:

((MountainBike)b2).shiftGearUp(); // This compiles and runs propperly 
0

“明白它 是引用变量的类型是很重要的 - 没有对象的类型它将 指向 - 确定哪些成员可以访问 。“

这意思是,编译器检查类的方法和其他成员的存在参考变量的,例如,假设你有一个Dog子类,其延伸Animal基类,

Animal obj=new Dog(); 
obj.makeSound(); 

这里编译器检查在动物类makeSound()方法是否申报或不为它编写。