默认包下跨类访问public实例变量报“cannot find symbol”问题咨询
解决c2类访问c1实例变量时的"cannot find symbol"错误
我定义了两个默认包下的类c1和c2,代码如下:
public class c1 { public int x, y, x1, y1; public static void main(String args[]) { c1 a = new c1(); } public c1() { c2 b = new c2(); b.getSlope(); } } public class c2 { public c2() {} public int getSlope() { return (y-y1)/(x-x1); } }
在c1的构造方法里,我实例化了c2并调用它的getSlope()方法,结果运行时报错"cannot find symbol"——原因很明显,c2和c1是两个完全独立的类,c2根本不知道c1里的x、y、x1、y1这些变量存在,自然无法直接访问。这里有几种可行的解决思路,你可以根据实际场景选择:
1. 将c1的实例传递给c2,让c2能引用到具体对象
你可以修改c2的构造方法,让它接收一个c1的实例并保存,之后在getSlope()里通过这个实例访问变量:
public class c1 { public int x, y, x1, y1; public static void main(String args[]) { c1 a = new c1(); } public c1() { // 创建c2时传入当前c1实例 c2 b = new c2(this); b.getSlope(); } } public class c2 { private c1 c1Instance; // 构造方法接收c1实例并保存 public c2(c1 instance) { this.c1Instance = instance; } public int getSlope() { // 通过保存的c1实例访问变量 return (c1Instance.y - c1Instance.y1) / (c1Instance.x - c1Instance.x1); } }
或者也可以直接把c1实例作为参数传给getSlope()方法,不用修改构造:
public class c1 { public int x, y, x1, y1; public static void main(String args[]) { c1 a = new c1(); } public c1() { c2 b = new c2(); // 调用getSlope时传入当前c1实例 b.getSlope(this); } } public class c2 { public c2() {} // 修改getSlope方法,接收c1实例参数 public int getSlope(c1 instance) { return (instance.y - instance.y1) / (instance.x - instance.x1); } }
2. 将c2改为c1的内部类
如果c2只是为c1服务的辅助类,完全可以把它定义成c1的内部类,这样内部类能直接访问外部类的实例变量:
public class c1 { public int x, y, x1, y1; public static void main(String args[]) { c1 a = new c1(); } public c1() { // 创建内部类实例 c2 b = new c2(); b.getSlope(); } // 定义内部类c2 class c2 { public c2() {} public int getSlope() { // 直接访问外部类c1的变量 return (y - y1) / (x - x1); } } }
3. 直接把需要的变量作为参数传给getSlope方法
如果不想让c2依赖c1类,可以把计算斜率需要的四个变量(或者直接计算好分子分母)作为参数传递给getSlope():
public class c1 { public int x, y, x1, y1; public static void main(String args[]) { c1 a = new c1(); } public c1() { c2 b = new c2(); // 传入四个变量 b.getSlope(y, y1, x, x1); } } public class c2 { public c2() {} // 接收四个变量参数 public int getSlope(int y, int y1, int x, int x1) { return (y - y1) / (x - x1); } }
内容的提问来源于stack exchange,提问作者xxsurajbxx
相关产品推荐
相关产品推荐

