我不是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
Run Code Online (Sandbox Code Playgroud)
定义此程序的输出.
我在采访中回答了这个问题,输出结果是运行时异常.根据我的理解,y被声明为private,而实例方法call()正试图访问另一个Q类实例的实例私有变量y.怎么会发生这种情况!?然而,错误地回答这个问题并没有太多影响我的采访,因为这是一种"棘手的基本"问题.但是,错误地回答意味着我多年的Java经验需要康复,这太糟糕了!
有人可以帮我解决这个问题吗?我将非常感激!
private只是意味着它不能被另一个类的对象访问,而不能被任何其他对象访问.因此,一个Q对象可以访问另一个Q对象的私有成员.
[ 请注意,如果这是非法的,这将触发编译器错误,而不是运行时异常.]