Saturday 15 January 2011

class - Inner classes in Java - Non static variable error -



class - Inner classes in Java - Non static variable error -

im still new java , tried create inner class , phone call method within main. theres compilation error saying "non static variable - cannot referenced static context"

please help

class class1{ public static void main(string args []){ class2 myobject = new class2(); myobject.newmethod(); } public class class2{ public void newmethod(){ system.out.println("second class"); } } }

an inner class needs reference instance of outer class in order constructed. if class doesn't logically need that, utilize static modifer create "just nested class":

public static class class2 { public void newmethod(){ system.out.println("second class"); } }

edit: create instance of class2 inner class, utilize like:

class1 outer = new class1(); class2 myobject = outer.new class2();

or more briefly:

class2 myobject = new class1().new class2();

... unless want reference enclosing instance, it's much simpler create class nested class.

java class inner-classes

No comments:

Post a Comment