2013年11月21日星期四

Java inner class a compilation error , help me find

I use Netbeans + jdk1.7 wrote a very small program :

public class JavaApplication1 {

    /**
     * @param args the command line arguments
     */
    public class Base
    {
        public Base() { f(); }
        public void f() { System.out.println("Base"); }
    }
    public class Derived extends Base
    {
        public Derived() { f(); }
        public void f() { System.out.println("Derived"); }
    }
    public static void main(String[] args) {
        // TODO code application logic here
        JavaApplication1.Base pb = new JavaApplication1.Derived();
    }
}

main function prompts the only word there is an error , "non-static variable cannot be referenced from a static context. May split declaration into a declaration ; and assignment ".

This in the end is what does this mean ?
------ Solution ------------------------------ --------------
public class Base
amended as follows:
public static class Base


Derived too.
------ Solution ---------------------------------------- ----
line 18 :
JavaApplication1.Base pb = new JavaApplication1.Derived ();

you write that part of the right side of the equal sign is used to define a static inner classes .


To define general internal class , should be written as :
JavaApplication1 ja1 = new JavaApplication1 ();
JavaApplication1.Base pb = ja1.new Derived ();

try it ~
defines common internal class object must have a peripheral (such as in this case JavaApplication1 class ) corresponding object .



------ Solution ------------------------------------ --------
because it is in the peripheral category (JavaApplication1) inner class defined inside the object , so can even be simplified to :
JavaApplication1 ja1 = new JavaApplication1 ();
Base pb = ja1.new Derived ();
------ Solution -------- ------------------------------------
Base Derived now JavaApplication1 outside the try.
------ Solution ---------------------------------------- ----
public class Base
amended as follows:
public static class Base


Derived too. quote 1 floor

in a static method can not call non-static methods

没有评论:

发表评论