non-static method toString() cannot be referenced from a static context

后端 未结 4 2009
长发绾君心
长发绾君心 2020-12-10 20:03

Don\'t want any code, just want some sort of guidance. Would like to keep my academic integrity in tact ;)

I keep getting that annoying error. I need to call the toS

4条回答
  •  执笔经年
    2020-12-10 20:29

    Look at the following code, you can compile toString with a static variable without a new object, it just throw exception at run time

    demo>cat Test.java 
    class Water {
      public String toString() {return "whatever";}
    }
    
    public class Test { 
      static Water water;
      public static void main(String...args) {
        System.out.println(water.toString());
      }
    }
    
    demo>javac Test.java 
    demo>java Test
    Exception in thread "main" java.lang.NullPointerException
        at Test.main(Test.java:8)
    

提交回复
热议问题