简体   繁体   中英

class within a class,conflict of same data member in both these classes

class A
{
    private int b;
    public A(int x)
    {
        b=x
    }
    public class B
    {
        int b;
        public B(int x)
        {
            b=x;
        }
        public void display()
        {
            System.out.println("b of outer class is"); //how can I refer to the b of class A?
            System.out.println("b of inner class is"+b);
        }
    }
}

There is a class defined within class,and is public,non static member of the outer class,now if there is a conflict between the outer class instance member and the inner class instance member that is with the same name how one can refer to the outer class instance data member.

Directly accessing b , is equivalent to this.b . In that context, this reference holds reference to the inner class instance. You need a reference to the enclosing instance, to access it's instance variable. Which you can do using A.this . So, to access b of class A , you can use A.this.b :

System.out.println("b of outer class is" + A.this.b);

In Java, it is possible to access object of the parent instance using A.this.

However, C# doesn't support accessing parent objects property directly. Therefore need to keep a reference of the outer instance inside the inner instance.

Below is an example with a little modification to the original:

class A
{
    private int count;
    private B _b;

    public A(int x)
    {
        count = x;
        _b = new B(this);
    }

    public class B
    {
        int count;
        private A _a;

        public B(A a)
        {
            this._a = a;
        }

        public void SetCount(int x)
        {
            count = x;
        }

        public void display()
        {
            System.Console.WriteLine("count of outer class is" + _a.count ); // parent count
            System.Console.WriteLine("count of inner class is" + this.count);
        }
    }

    public B b
    {
        get { return _b; }
        set { _b = value; }
    }
}

public class TestCount
{
    public void TestDisplay()
    {
        A a = new A(10);
        a.b.SetCount(5);
        a.b.display();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM