无法从静态上下文引用非静态变量名称 [英] non static variable name cannot be referenced from a static context

查看:136
本文介绍了无法从静态上下文引用非静态变量名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Singer
{
 String name;
 String album;

 public Singer(){
  name="Whitney Houson";
  album="Latest Releases";
 }

 public static void main(String[] args) 
 {
  System.out.println("Name of the singer is "+name);
  System.out.println("Album Information stored for "+album);

 }
}

当我运行此代码时,我是发现错误,表示非静态变量名称无法从静态上下文引用

When i run this code i am finding error which says that non static variable name cannot be referenced from a static context

推荐答案

这是因为变量名称和相册不存在于主过程中,因为它是静态的,这意味着它无法访问实例级成员。你需要一个Singer类的实例,如下所示:

That's because the variables name and album do not exist in the main procedure, because it's static, which means it cannot access instance-level members. You will need an instance of the Singer class, like this:

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()等),以便从封装中受益。像这样:

However, unless you declare your name/album members with a public access modifier, the above code will fail to compile. I recommended writing a getter for each member (getName(), getAlbum(), etc), in order to benefit from encapsulation. Like this:

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());

 }

}

另一种选择是要将名称和专辑声明为静态,然后您可以按照原定的方式引用它们。

Another alternative would be to declare name and album as static, then you can reference them in the way you originally intended.

这篇关于无法从静态上下文引用非静态变量名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆