java - 创建对象的引用

标签 java

我有一个关于 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 包含方法 sumgetRandom 。但是当我们尝试通过 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/

相关文章:

java - 音频文件的语音转换器

java - 从内部类引用的局部变量必须是 final 或有效的 final

java - Scribe 的 Oauth 问题

java - Spring MVC Controller 与属性文件的映射

java - 使用 java 套接字的基于控制台的登录应用程序

java - 将我的应用程序 Activity 实例添加到 Lollipop 上的最近使用

java - 无法找到或加载主类 com.android.sdkmanager.Main

java - 如何创建以数据表为可排序项目的列表

javascript - 在新浏览器选项卡上时的最终用户 session

java - 在运行时获取 JVM 编译器阈值