简体   繁体   中英

OOP - Who can access to public, private, protected variable?

I'm new to OOP. Look at following pseudo code:

Class Test{
   public String a;
   protected String b;
   private String c;
   public void aa(){}
   protected void bb(){}
   private void cc(){}
   Class Test2{
      private void dd(){}
   }
}
Class Test3 extends Test{
   private void ee(){}
}
Class Test4{
   private void ff(){}
}

Can a , b and c access into aa() , bb() and cc() ? Can a , b and c access into the class Test2 and dd() ? Is true that only a and b can access into the class Test3 and ee() ? Is true that only a can access into the class Test4 and ff() ?

For the first question
"Can aa() access a,b,c of class Test" : Yes it can access member of its outer class. Test2 is an inner class and an inner class is associated with an instance of its enclosing class and has direct access to that object's methods and fields

for second question
"Is true that only a and b can access into the class Test3" : Yes a,b can be accessible inside class Test3. Subclass can access Public and Protected members of its base class.

for third one
"Is true that only a can access into the class Test4?" : Yes, only 'a' can be accessed inside class Test4 if you make an object of class Test and access it by using dot(.) operator.

  • private - Only the class protected

  • Protected Those that inherit

  • Public the world

What you're talking about are called access-modifiers in java. You have mentioned three of them but there are in total 4 types of access modifiers :

  1. private - They are not visible to anybody except to members of the class they reside in.
  2. protected - private + Visible to sub-classes as well.
  3. default - private + other classes in the same package.
  4. public - Visible to the entire universe.

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