2013-06-23 107 views
1

完整的java noob,在这里。目前教我自己。最近,我尝试制作一个基本程序,它将使用一个班级从另一个班级获取信息,并将其打印出来。我不断收到此错误:如何访问另一个类中的类变量?

error cannot find symbol 

System.out.print1n(ljames.weight); 

symbol: variable weight 
location: class ljames 

这里是我的代码:

http://shrib.com/sEyGhFZr

请帮助我。

回答

0

我想这只是变量的可见性。您没有声明这些变量是公开的,并且其他类不可访问。

你声明你的函数是公开的,它们可以从其他地方访问。

我建议创建一个公共构造函数并为您的变量创建get-accessors。你通过构造函数设置它们并通过get-accessor读取它们。这样您可以保证数据的安全,并且在需要时仍可以进行更改。

class Data { 
    String height; 
    int weight; 
    int depth; 
    public Data(String height, int weight, int depth) { 
     this.height = height; 
     this.weight = weight; 
     this.depth = depth; 
    } 
    public string getHeight() { 
     return height; 
    } 
    public int getWeight() { 
     return weight; 
    } 
    public int getDepth() { 
     return depth; 
    } 
} 
+0

谢谢你。我想我已经越过了我的脑海。我目前正在从“山姆在21天内教自己的Java”一书中学习。一切对我来说都是新鲜的。花了一段时间来围绕面向对象的编程进行思考。无论如何,我在第4天:列表,逻辑和循环。原来我在第6天学习构造函数。冲我自己。 –

+0

@AbdiAbdalla开始是真正的痛苦。当你终于掌握了你的第五种语言时,一切都变得看起来一样,并且你再也没有任何问题了。 :)(我自己是Java的新手^^) – bash0r

0

ljames没有现场命名重量,因为这是在数据类。

+0

他在主函数内用'Data'类型的变量覆盖类名。它缺乏导致问题的可见性。但你是对的,他应该重新命名课程或变量。 – bash0r

+0

我点击链接时看到的代码没有任何Ijames extends Data,也没有任何“新ljames()”。它令人困惑。 – clearwater

相关问题