0

I'm trying to visualize real time or hypothetical example (Human body, bus etc any existence in nature) to differentiate between static and non static nested classes. Its little strange question, but I think its good relate with real world :)

Usually I follow below concept

class A
{
    class B
    {
        // static int x; not allowed here
    }

    static class C
    {
        static int x; // allowed here
    }
}

class Test
{
    public static void main(String… str)
    {
        A a = new A();

        // Non-Static Inner Class
        // Requires enclosing instance
        A.B obj1 = a.new B(); 

        // Static Inner Class
        // No need for reference of object to the outer class
        A.C obj2 = new A.C(); 
    }
}

But its something just code and formula to code. But am curious to know how people understand with any hypothetical scenario if any.

Please share..!

JonLe
  • 71
  • 2
  • 7
  • @ Hovercraft Full Of Eels, I know answer is given, but am looking some real world example. Please understand – JonLe Feb 02 '20 at 15:01
  • Keep looking. You have the whole internet at your fingertips. – Kayaman Feb 02 '20 at 15:02
  • @hqt, Have seen all these..! But these are explaining only coding perspective. Looking for real world example ..to example someone very lame – JonLe Feb 02 '20 at 15:02
  • Please take a look at this: https://stackoverflow.com/questions/18396016/when-to-use-inner-classes-in-java-for-helper-classes – hqt Feb 02 '20 at 15:03
  • 1
    @JonLe Imagine that a nested class cannot be instantiated without instantiating the parent class. So, you cannot have a head without a person. The exception is a static nested class. A static nested class can be instantiated without instantiating the parent. See also the links provided by the others. – Menelaos Feb 02 '20 at 15:11
  • @MenelaosBakopoulos By "parent" you probably meant "outer" class. Anyway nice example with Body and Head analogy. – Pshemo Feb 02 '20 at 15:12

0 Answers0