这是被引用,因为变量名和相册不存在于主程序中,因为它是静态的,这意味着它不能访问实例级别的成员。您将需要歌手类的一个实例,像这样:
public static void main(String[] args) {
Singer s = new Singer();
System.out.println("Name of the singer is " + s.name);
System.out.println("Album information stored for " + s.album);
}
但是,除非你有一个公共访问修饰符声明你的名字/专辑的成员,上面的代码将无法编译。我建议为每个成员写一个getter(getName(),getAlbum()等),以便从封装中受益。像这样:
class Singer {
private String name;
private String album;
public Singer() {
this.name = "Whitney Houston";
this.album = "Latest Releases";
}
public String getName() {
return this.name;
}
public String getAlbum() {
return this.album;
}
public static void main(String[] args) {
Singer s = new Singer();
System.out.println("Name of the singer is " + s.getName());
System.out.println("Album information stored for " + s.getAlbum());
}
}
另一种方法是将名称和专辑声明为静态,然后您可以按照您最初的设计方式引用它们。
'... + s.name); ... + s.album);' – khachik 2010-11-19 16:01:57
顺便说一句,上面的代码将编译并运行良好,如果名称是私有的,因为'main'也属于'Singer'。 – khachik 2010-11-19 16:05:04