gpt4 book ai didi

java - 一个简单Java的棘手问题: variable scope

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

我对 Java 和 C# 并不陌生。直到最近我在面试中被问到这个问题之前,我一直以为我了解变量范围的概念:

public class Q{ //starting y scope

static int x = 11;
private int y = 33; // Just added a “private” modifier to make it clearer.

public static void main(String args[]){
Q q = new Q();
q.call(5);
}

public void call(int x){
Q q = new Q();

this.x = 22;
y = 44;

System.out.println("Output: " + Q.x);
System.out.println("Output: " + q.x);
System.out.println("Output: " + q.y);
}

} //ending y scope

定义这个程序的输出。

我在采访中回答了输出将是运行时异常的问题。据我了解,y 被声明为私有(private)的,并且实例方法 call() 试图访问类 Q 的另一个实例的实例私有(private)变量 y。这怎么可能发生!?不过答错这道题并没有对我的面试造成太大的影响,因为这是那种“tricky basic”的题。但是,回答错误意味着我多年的 Java 经验需要修复,这太糟糕了!

有人可以帮我解决这个问题吗?我将不胜感激!

最佳答案

您可以访问您自己类的 private 成员,甚至可以从该类的不同实例访问。

关于java - 一个简单Java的棘手问题: variable scope,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6426279/

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