Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I did read a number of topics discussing inner classes, and i was under the impression that an inner class has access to the variables and methods of the enclosing class. In the following i have an outer class and an inner class, in the test class i create an instance of the outer class and then from that i create an instance of the inner class. However i am not able to access the String variable a through the inner class reference. Help?

public class OuterClass {

    String a = "A";
    String b = "B";
    String c = "C";

    class InnerClass {
        int x;

    }

    public static class StaticInnerClass {
        int x;
    }

    public String stringConCat() {
        return a + b + c;

    }
}

public class TestStatic {

    public static void main(String args[]) {

        OuterClass.StaticInnerClass staticClass = new OuterClass.StaticInnerClass();
        OuterClass outer = new OuterClass();
        OuterClass.InnerClass inner = outer.new InnerClass();

        System.out.println(inner.a);// error here, why can't i access the string
                                    // variable a here?

    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
278 views
Welcome To Ask or Share your Answers For Others

1 Answer

The inner class can access the outer class methods and properties through its own methods. Look at the following code:

class OuterClass {

    String a = "A";
    String b = "B";
    String c = "C";

    class InnerClass{
        int x;
        public String getA(){
            return a; // access the variable a from outer class
        }
    }

    public static class StaticInnerClass{
        int x;
    }

    public String stringConCat(){
        return a + b + c;    
    }
}


public class Test{

    public static void main(String args[]) {

        OuterClass.StaticInnerClass staticClass = new OuterClass.StaticInnerClass();
        OuterClass outer = new OuterClass();
        OuterClass.InnerClass inner = outer.new InnerClass();

        System.out.println(inner.getA()); // This will print "A"
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...