开发者

object created within a class gets access to private fields.. and objects created in a different class don't why?

开发者 https://www.devze.com 2023-03-15 04:45 出处:网络
First of all i created a class called PrivateShirt1 and called a private field name after creating an object of the class within the same class file, and it worked.

First of all i created a class called PrivateShirt1 and called a private field name after creating an object of the class within the same class file, and it worked.

public class PrivateShirt1{
   private String name;

   public static void main(String args[]){               
       Pr开发者_C百科ivateShirt1 s1=new PrivateShirt1();
       s1.name="hi";

       System.out.println(s1.name);    
   }
}

next i created a separate file called PrivateShirt2 in which i put the main method of PrivateShirt1 and performed the function of compiling and calling it. After the modifications the files PrivateShirt1 and PrivateShirt2 look like this:

public class PrivateShirt2{ 

  public static void main(String args[]){               
     PrivateShirt1 s1=new PrivateShirt1();
     s1.name="hi";

     System.out.println(s1.name);    
  }


public class PrivateShirt1 {
   private String name;    
}

and when i compiled the PrivateShirt2 file, it gave an error that the attribute i was trying to call is private.

but then why did this not happen in the previous example? I mean, objects were created in both the cases and hence the rules should be equal for both, right? so why then this partial treatment? could anyone elaborate?


You need to look at java access control. The name variable in PrivateShirt1 has private access. Meaning that field can only be referenced from inside that class. PrivateShirt2 does not have access to that field. The reason your first call worked is because it was called within PrivateShirt1

http://download.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html


private modifier means that you can access it only from the code in the Class. Therefore you can access a private member from a static method or even an inner class.

0

精彩评论

暂无评论...
验证码 换一张
取 消