简体   繁体   中英

In case of inner and outer classes, Java

There was one MCQ ( Multiple Choice Question ) while I was reading my Java study book and that MCQ is:

Question : In case of inner and outer classes, _________

Options are :

(a) The members of outer class can not be accessed by inner class.

(b) The members of inner class can not be accessed by outer class.

(c) Members of both can be accessed by both of the classes.

(d) None of these.

The answer given on book answer key is (b) but I'm not feeling it as right answer because outer class can access members of its inner class I think. So please help me with what is right.

Thanks, have a good day :)

Sorry for the confusion.

You can access inner and outer classes both ways. I do suggest trying a simple example though yourself as programming is one of those things you only learn through your own problems.

Refer to this as this may help: Can an outer class access the members of inner class?

lets make it simple with some code

public class A {
    public int a = 1;
    public class B {
        public int b = 2;
        public int getAfromB() { return a; } // ACCESS OUTER CLASS MEMBER IMPLICITLY
        public int getBfromB() { return b; }
    }
    public int getBfromA() {
        B myB1 = new B();
        B myB2 = new B();
        return myB1.b + myB2.b; 
    }
}

An B instance is linked to a specific A instance, it belongs to the instance scope. In its scope, the members of the A class are defined.

The A class can handle several instances of the B class. It will be able to manipulate them but cannot implicitly access a specific instance members, simply because 'b' is not unique from its perspective.

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