我有一个关于 java 中对象引用的概念性问题。
这里Num是一个接口(interface)
public interface Num {
void sum();
}
实现 Num 的 Num2
public class Num2 implements Num{
@Override
public void sum() {
System.out.println(getRandom()+getRandom());
}
public int getRandom() {
Random randomNumber = new Random();
int number = randomNumber.nextInt(30);
return number;
}
}
主要功能
Num n = new Num2();
n.sum();
这里我知道n是对象Num2的引用,n是指向对象Num2的指针。 Num2 包含方法 sum 和 getRandom 。但是当我们尝试通过 n 引用访问方法时,我们只能得到 sum强> 方法。我的问题是指针如何知道 Num 中包含哪些方法。对象初始化过程中如何以及哪些信息存储在堆栈中以供引用。如果我有任何误解,请纠正我。
最佳答案
您将变量 n
定义为 Num
接口(interface)类型,因此您只能调用在 Num
中声明的方法。我相信这个决议是在编译时本身完成的。编译器通过使用基于其类型的引用变量来确定哪些字段或方法是可访问的。
但请记住,运行时将调用实际对象类型上的方法,即实现接口(interface)的类。
A variable of a class type T can hold a null reference or a reference to an instance of class T or of any class that is a subclass of T.
看下面的代码:
interface A {
void method1();
}
class B implements A {
public void method1() {
}
public void methodB(){
}
}
class C implements A {
public void method1() {
}
public void methodC(){
}
}
public class InterfaceTest {
public void testMethod(A a){
// this is safe because whatever may be the run time type of actual
// object `a` is referring to , that object will always implement
// method1.
a.method1();
// this cannot be allowed because compiler doesn't know
// what will be the actual run time object `a` will refer to
// It may or may not be an object of B.
a.methodB();
}
}
关于java - 创建对象的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17849164/