jeudi 4 juin 2020

How to access outer class fields from static inner class? [duplicate]

I have a question about accessing outer non-static class fields within a static inner class.

Lets have a piece of code:

public class Outer implements AutoCloseable {

    public Outer(int outerVar) implements Runnable {
        this.outerVar = outerVar;
        inner = new Inner(outerVar);
        cleanable = cleaner.register(this, inner);
    }

    int outerVar;
    private static final Cleaner cleaner = Cleaner.create();
    private final Inner inner;

    public int getOuterVar() {
        return outerVar;
    }

    public static class Inner {

        int innerVar = //some way to get the outerVar value

        @Override
        public void run() {
        System.out.println("Czyszczenie pokoju");
        outerVar = 0;
    }

    @Override
    public void close() throws Exception {
        cleanable.clean();
    }

}      

I have tried doing Outer.this.getNumJunkPiles(); but this obviously gets red in my IntelliJ and says: Outer.this' cannot be referenced from a static context

Is there a way to access the non-static outer variable from a static inner class?





Aucun commentaire:

Enregistrer un commentaire