Chameleon
Chameleon

Reputation: 10138

How to access parent class member from nested class in 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.

Upvotes: 51

Views: 57525

Answers (2)

Lopes_CP_CR2807
Lopes_CP_CR2807

Reputation: 5

How about if you change one of the String id.

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

  class Child {
    // it is invalid since scope hide parent id?
    // Instead of using id use ID
    final String ID = id;
  }
}

This way you would not have string id = id, which does not make sense.

Upvotes: -7

assylias
assylias

Reputation: 328855

You can access it by using its fully qualified name:

final String id = Parent.this.id;

Upvotes: 115

Related Questions