我以为内部类可以访问外部类变量/方法? [英] I thought inner classes could access the outer class variables/methods?

查看:380
本文介绍了我以为内部类可以访问外部类变量/方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我确实阅读了许多讨论内部类的主题,我的印象是内部类可以访问封闭类的变量和方法。在下面我有一个外部类和一​​个内部类,在测试类中我创建了一个外部类的实例,然后从中创建了一个内部类的实例。但是我无法通过内部类引用访问String变量a。救命?

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?

    }
}


推荐答案

内部类可以通过自己的方法访问外部类方法和属性。请查看以下代码:

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

这篇关于我以为内部类可以访问外部类变量/方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆