java - Can I declare inner class as a static and access it without creating an object in surrounding class? -
i read static can applied nested class.so out creating object can accessible. getting output.
string stored in str is- inside class example1 code:
class example1{ //static class static class x{ static string str="inside class x"; } public static void main(string args[]) { x.str="inside class example1"; system.out.println("string stored in str is- "+ x.str); } }
your codes works fine, without errors.
you can access static method /field of static inner class, without creating object of static inner class. if want access non-static method/fields of static inner class class, required create object of static inner class.
class example1 { // static class static class x { static string str = "inside class x"; public void display() { system.out.println("i in display method"); } } } public class staticinnerdemo { public static void main(string[] args) { //accessing static field of static inner class example1.x.str = "inside class example1"; system.out.println("string stored in str is- " + example1.x.str); //accessing non static method of static inner class. example1.x ob = new example1.x(); ob.display(); } }
Comments
Post a Comment