I
I
Igor2018-12-13 20:02:38
Java
Igor, 2018-12-13 20:02:38

Java: how to access a field from a nested class?

class Test {
  private String outerString = "КО КО КО";
  class innerTest {
    Test.this.outerString = "ПОК ПОК ПОК";
  }
}

How can I access a field in an outer class from a nested class?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2018-12-13
@hddn

You are trying to perform an assignment at the class definition level, which is interpreted by the compiler as an attempt to declare a Test.this.outerStringclass field innerTest, which is naturally impossible. And inside any method you will not have access problems

class innerTest {
    void someMethod() {
        Test.this.outerString = "ПОК ПОК ПОК";
        // или даже проще
        outerString = "ПОК ПОК ПОК";
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question