You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中如何访问对象的内部变量?代码调用报错原因咨询

为什么t1.result这条语句会无效?

嘿,这个问题其实是Java变量作用域的基础知识点,咱们一步步拆解原因:

你在test1类的构造函数里声明的int result是局部变量,它的作用域被严格限制在构造函数的代码块内部。也就是说,一旦构造函数执行完成,这个变量就会被Java的垃圾回收机制清理掉,外部代码(比如invoke类的main方法)根本看不到它的存在,自然没法通过对象实例t1去访问它。

怎么修改才能访问到这个值?

如果你希望result的值能被对象实例持有并外部访问,需要把它声明为类的成员变量(实例变量),而不是构造函数里的局部变量。这里给你两种常见的实现方式:

方式1:遵循封装原则(推荐)

把result设为私有成员变量,通过getter方法对外提供访问路径:

public class test1 { 
  // 声明为类的私有实例变量
  private int result;

  public test1(int bigNumber, int smallNumber) { 
    // 给实例变量赋值
    this.result = bigNumber - smallNumber; 
  }

  // 提供getter方法访问私有变量
  public int getResult() {
    return result;
  }
} 

class invoke { 
  public static void main(String[] args) { 
    test1 t1 = new test1(10, 5); 
    // 通过getter方法获取值,输出5
    System.out.println(t1.getResult()); 
  } 
}

方式2:直接设为public(仅用于快速测试,不推荐)

如果只是临时测试,可以把result设为public直接访问,但这种做法会破坏Java的封装特性,实际项目里尽量避免:

public class test1 { 
  public int result; // 设为public成员变量

  public test1(int bigNumber, int smallNumber) { 
    this.result = bigNumber - smallNumber; 
  }
} 

class invoke { 
  public static void main(String[] args) { 
    test1 t1 = new test1(10, 5); 
    System.out.println(t1.result); // 现在可以正常访问,输出5
  } 
}

简单总结:局部变量的作用域仅限于所在代码块,类的成员变量才属于对象实例,能被外部通过实例访问(前提是权限允许)。

内容的提问来源于stack exchange,提问作者TheOddy Linux

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:30:07