-5
public class A {
    private String str;
    public void setString(String pStr){
        str = pStr;
    }

    private class B {
        public String getStr(){
            return str;
        }
    }
}

a)What is the relation between class A and class B ? b)And why Class B can access private field of A (str) ?

Is it derived or other else?

Don Roby
  • 40,677
  • 6
  • 91
  • 113
John Law
  • 15
  • 7
  • you need to do your homework. it's **your** homework and not ours, for a reason. and no, these two classes are not related in any immediately meaningful way (you could come up with artificial stuff like "the same programmer wrote them", but that's irrelevant, presumably.) – The Paramagnetic Croissant Feb 15 '15 at 13:59

4 Answers4

0

class B is private so it only can be created from within the class. That means that class A is always present in some form. When you make class B static you wont have any access to class A's variables because it is static.

engineercoding
  • 832
  • 6
  • 14
0

It's just an nested class i.e. class within class. It's similar to you defining field and passing value like say private String mystr = new String(str); So here you can access private field str and pass it onto String.

Similarly you have defined non static class within the outer class which would access private/protected/public field defined in outer class.

You call a class as derived, if say it extends another class. Something like:

public class MyParentClass {}
public class MySubClass extends MyParentClass {}
SMA
  • 36,381
  • 8
  • 49
  • 73
0

Answers: a) There is no relationship between one and the other as you have shown in b) Class B can't access it because it is private on A and there is no relationship (read inheritance) in the code shown between the two. Even if there was, privates are not inherited

Take a look at these links to better understand inheritance and private properties:

Community
  • 1
  • 1
Jaquio
  • 183
  • 1
  • 11
0

Class B is kind of member of class A. When a class has a private member, other members of the same class can have access to it. Same way class B can access private members of class A in your case. This is not a relationship of any kind. It is just class within the class.