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

Categories

0 votes
280 views
in Technique[技术] by (71.8m points)

java - I thought inner classes could access the outer class variables/methods?

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

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

1 Answer

0 votes
by (71.8m points)

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"
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...