Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access parent class member from nested class in Java?

Tags:

java

Simple question for Java programmer - I am not sure if it possible directly - please present workarounds.

I want to access parent variable to initialize nested class member but not know the Java syntax to do it (if it possible). How to set Child id with parent id.

public class Parent {
    final String id = "parent";

    class Child {
        // it is invalid since scope hide parent id?
        final String id = id;
    }
}

The best solution with I found is very ugly see here:

public class Parent {
    final String id = "parent";

    // ugly clone
    String shadow = id;

    class Child {
        final String id = shadow;
    }
}

Please help with syntax - I do not know how to express it.

like image 623
Chameleon Avatar asked Feb 10 '13 17:02

Chameleon


1 Answers

You can access it by using its fully qualified name:

final String id = Parent.this.id;
like image 50
assylias Avatar answered Nov 01 '22 17:11

assylias