Java - How to access Outer class field if the fields have same name

后端 未结 5 2043
长发绾君心
长发绾君心 2021-01-26 02:26

Consider the following code

class OuterClass{
    class InnerClass{
        int x;
        int y;
        void calculateX(){
            x = y+z;//I want to acce         


        
5条回答
  •  野性不改
    2021-01-26 03:15

    The best solution is to give the fields meaningful and distinguishing names. But this is not always possible...

    To get a field or an outer instance you can use

    OuterClass.this.y;
    

    or if the field is static

    OuterClass.y;
    

    Note: y is often short for this.y (depending on where y actually is defined)

    Similarly, to call an instance method of an outer class you need.

    OuterClass.this.method();
    

    or

    OuterClass.method(); // static
    

    Note: in Java 8 you have method references which might be instance based. e.g.

     list.stream().filter(OuterClass.this::predicate);
    

提交回复
热议问题