请看代码public class test {
    public static void main(String[] args) {
    }
    public int ok = 123;
}
class test2 {
    static test t;
    System.out.println(t.ok);
}请问这样可以印出ok的值吗?如果不行要怎么做?

解决方案 »

  1.   

    public class test {
        public static void main(String[] args) {
         new test2();
        }
        public int ok = 123;
    }
    class test2 {
        static test t;
        public test2() {
         System.out.println(t.ok);
        }
    }这样的确不行的,会抛出空指针异常!请问要怎么做才能在其他类中取得ok的值?
      

  2.   

    public class Test2{
    static Test t = new Test();
        public static void main(String[] args) {
         System.out.println(t.ok);
        }
        
    }
    class Test {
        
        public int ok = 123;
        
    }
      

  3.   

    谢谢楼上的仁兄,但是我想在其他class中访问public class中的变量,这样不行吗?
      

  4.   

    public   class   test   { 
            public   static   void   main(String[]   args)   { 
            new   test2(); 
            } 
            public   int   ok   =   123; 

    class   test2   { 
            static   test   t = new test(); 
            public   test2()   { 
            System.out.println(t.ok); 
            }