What is difference between static and non-static inner class

What is difference between static and non-static inner class

Answer : Below are difference between a static and non-static inner class:

static inner class

non-static inner class

A non-static class or inner class has full access to its members of the class within which it is createdstatic nested class cannot invoke non-static methods or access non-static fields of an instance of the class within which it is created
Static inner class can declare both static and non- static membersNon static inner class cannot declare static field and static methods
static methods can access to its static members of main class and cannot access non static inner class members. You can access members of non-static inner class after create object of non-static inner class.Non-static inner class cannot access static member of the class within it created

Example:

package com.javahonk.staticTest;

public class StaticTest {

    String var = "non-static inner class";
    static String var2 = "Static inner class";

    static class innserStaticTest {
	void staticClassMethod() {
	    System.out.println(var2);
	}
    }

    class nonStaticTest {
	void nonstaticClassMethod() {
	    System.out.println(var);
	    System.out.println(var2);
	}
    }

    public static void main(String args[]) {
	innserStaticTest iStaticTest = new innserStaticTest();
	iStaticTest.staticClassMethod();

	StaticTest staticTest = new StaticTest();
	StaticTest.nonStaticTest noStaticTest = 
		staticTest.new nonStaticTest();
	noStaticTest.nonstaticClassMethod();

    }

}

 

Output:

Static inner class
non-static inner class
Static inner class

 

Leave a Reply

Your email address will not be published. Required fields are marked *