【问题标题】:Java-Cannot make a static reference to the non-static field [duplicate]Java-无法对非静态字段进行静态引用[重复]
【发布时间】:2017-05-15 10:00:58
【问题描述】:

好的,所以多年后我正在重新访问java,当我发现我在以下sn-p中出错时,我只是在尝试一些随机程序。有人可以告诉我如何解决这个问题吗?我知道静态方法将无法访问非静态变量,但我为它创建了一个实例,对吗?另外,我对阅读其他一些问题没有任何头绪,所以请尝试帮助我。

 import java.io.*;
    public class phone
    {
        int x=6;
        int getx()//I also tried using this function but everything in vain
        {
            return x;
        }
    }
    public class Testing_inheritance extends phone
    {
        public static void main (String args[])throws IOException
        {   
            phone xy=new phone();
            int y=phone.x;
            y+=10;
            System.out.println("The value of x is " +y);
        }
    }

【问题讨论】:

  • int y=phone.x; 应该是int y=xy.x;
  • 下次请附上控制台输出。

标签: java static static-methods


【解决方案1】:

您可能打算访问您创建的实例的实例变量:

        phone xy = new phone();
        int y = xy.x;

由于x 不是静态变量,如果不指定phone 类的实例,就无法访​​问它。

当然这也会失败,除非您将x 的访问级别更改为public(这是可能的,但不建议使用——您应该使用getter 和setter 方法,而不是直接从类外部操作实例变量) .

【讨论】:

  • 老兄,在使用静态变量时,这两种方法都有效,在这种情况下,使用 phone.x 更有意义,因为它是一个类变量
  • 如果我做 xy.x 我得到了错误:公共类型的电话必须在它自己的文件中定义
  • @IshanSrivastava 但是x不是静态变量,所以你不能使用phone.x
  • @IshanSrivastava 这是一个不相关的错误,它不言自明。每个公共类必须在一个单独的文件中,名称为 ClassName.java。
  • 好的,谢谢,对不起,我对什么是静态的,什么不是。
【解决方案2】:

x 不是static。您需要通过对象引用来访问它。

int y = xy.getx(); //could do xy.x, but better to access through method

此外,最好坚持 Java 命名约定

【讨论】:

    【解决方案3】:

    差不多完成了,我做了一些很小但非常重要的更改,希望你能得到这个,否则就问吧 ;-)

    电话.java

    public class Phone //<--- class with capital letter always
    {
        int x=6;
        int getx()//I also tried using this function but everything in vain
        {
            return x;
        }
    }
    

    Testing_inheritance.java

    import java.io.*;
    
        public class Testing_inheritance extends Phone
        {
            public static void main (String args[])throws IOException
            {   
                Phone xy=new Phone();
                int y= xy.getx(); //<--- principle of encapsulation
                y+=10;
                System.out.println("The value of x is " +y);
            }
        }
    

    或私有内部类:

      import java.io.IOException;
    
    public class Phone {
        int x = 6;
    
        int getx()// I also tried using this function but everything in vain
        {
            return x;
        }
    
        private static class Testing_inheritance extends Phone {
            public static void main(String args[]) throws IOException {
                Phone xy = new Phone();
                int y = xy.getx();
                y += 10;
                System.out.println("The value of x is " + y);
            }
    
        }
    }
    

    【讨论】:

    • 没错,否则它应该是一个私有类,你可以注意到我将它分为两​​个类,Phone.java 和 Testing_inheritance.java,你应该这样做或声明为私有类
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-19
    • 1970-01-01
    • 2015-11-30
    • 2021-08-31
    • 2014-02-02
    • 2013-02-25
    相关资源
    最近更新 更多