如何在外部类

时间:2017-11-01 09:04:17

标签: java inner-classes

想象一下如下所述的情景 -

public class TestMain {

    private int outerData = 30;

    class InnerFirst{
        private int data1 = 40;

        public int getData() {
            return data1;
        }

        public void setData(int data) {
            this.data1 = data;
        }

        void msg(){
            System.out.println("Inner data is : "+data1+" and outer data is : "+outerData);
        }
    }

    class InnerSecond{
        private int data2 = 40;

        public int getData() {
            return data2;
        }

        public void setData(int data) {
            this.data2 = data;
        }

        void msg(){
            System.out.println("Inner data is : "+data2+" and outer data is : "+outerData);
        }
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        TestMain newClass = new TestMain();
        TestMain.InnerFirst newInnerClass = newClass.new InnerFirst();

        newInnerClass.setData(50);

        newInnerClass.msg();





    }

}

我的目的是将newClass对象设置为session并在需要时访问它。但是我怎样才能访问data1(内部类实例变量)呢? 据我所知,newInnerClass对象(InnerFirst的对象)在newClass实例(外部类)中创建。我的问题是,如何从外部类对象引用访问内部类实例成员?

1 个答案:

答案 0 :(得分:1)

您始终可以在子类中保留这些子类的实例变量,并且在创建子类的对象时,可以在子类的构造函数中初始化同一类的实例变量。像这样:对于第二类,你可以做同样的事情:你可以使用这个实例变量从子类中获取每个字段。

public class TestMain {

private  InnerFirst first;
private InnerSecond second;

private int outerData = 30;

class InnerFirst{
    private InnerFirst() {
        first = this;
    }



    private int data1 = 40;

    public int getData() {
        return data1;
    }

    public void setData(int data) {
        this.data1 = data;
    }

    void msg(){
        System.out.println("Inner data is : "+data1+" and outer data is : "+outerData);
    }
}

class InnerSecond{
    private InnerSecond() {
        second = this;
    }

    private int data2 = 40;

    public int getData() {
        return data2;
    }

    public void setData(int data) {
        this.data2 = data;
    }

    void msg(){
        System.out.println("Inner data is : "+data2+" and outer data is : "+outerData);
    }
}



private InnerFirst getFirst() {
    return first;
}


public static void main(String[] args) {
    // TODO Auto-generated method stub
    TestMain newClass = new TestMain();
    TestMain.InnerFirst newInnerClass = newClass.new InnerFirst();
    System.out.println(newClass.getFirst().getData());        

    newInnerClass.setData(50);

       newInnerClass.msg();

}

}