Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why wouldn't you make a nested class static?

If I have class with a nested class, why wouldn't you want it to be static? Is there even a way for two instances of the same class to have different nested classes?

For example:

class MyClass {  
    public static class myInnerClass {

    }
}
like image 748
Lerp Avatar asked Dec 21 '22 12:12

Lerp


2 Answers

why wouldn't you want it to be static

Because I want it to access instance data of a parent object.

Is there even a way for two instances of the same class to have different nested classes?

What do you mean by have? Declared? A class has only one declaration where you list all nested classes. So, in this case the answer is no.

like image 195
tcb Avatar answered Dec 26 '22 00:12

tcb


Take for example a Comparator or Runnable (multi-threading) implementations. This is a classic example when you need an extra class that has access to the current instance's fields and methods but is of no use outside of that class. However, static classes could be useful outside the enclosing type, too.

public class EnclosingType
{

    private static final class StaticRunnableImplementation implements Runnable
    {
        private final EnclosingType instance;

        public StaticRunnableImplementation(EnclosingType instance)
        {
            this.instance = instance;
        }

        @Override
        public void run()
        {
            instance.getSomething();
            //getSomething() leads to compile error
        }
    }

    public class NonStaticRunnableImplementation implements Runnable
    {
        @Override
        public void run()
        {
            doStuff();
        }

    }

    public int getSomething()
    {
        return 42;
    } 

    public synchronized void doStuff()
    {
        ;
    }

    public void doSomething()
    {
        Thread t1 = new Thread(new StaticRunnableImplementation(this));
        Thread t2 = new Thread(new NonStaticRunnableImplementation());

        t1.start();
        t2.start();
    }
}

The access to the non-static methods and fields of current instance of the enclosing type, wouldn't be possible if the nested classes would be declared static.

like image 28
Simon Avatar answered Dec 25 '22 23:12

Simon