gpt4 book ai didi

Java - 引用变量

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:27:07 27 4
gpt4 key购买 nike

" It is important to understand that it is the type of reference variable - not the type of object that it refers to - that determines what members can be accessed. "

你所说的到底是什么意思?这仅限于继承的概念吗?JVM 如何处理它?<​​/p>

最佳答案

这意味着假设你有:

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)

关于Java - 引用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2500555/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com