Friday, July 31, 2009

In Java if you do not explicitly declare accessor type for instance variable what accessor type is assigned?

For example if you have





public class Example{


int someNum;


}





What accessor type is assigned to someNum by the java compiler. Is it public or protected?

In Java if you do not explicitly declare accessor type for instance variable what accessor type is assigned?
If you use the default visiblity it is "package" visibility. Meaning that field or method is visible to other objects and classes in the same java package.
Reply:NetBeans will not let you assign an accesor to instance variables-- after the constructor, and that's logical, only class-definition variables need the degrees of visibility -- defined outside the constructor.





In your example, you have the default visibility accessor... meaning that only a class within that same package can see int someNum. Default and final are the other accessors -- like protected and private.
Reply:That's a good question. I didn't readily find the answer but it would be most logical for them to be private, so that they are only accessible within the class. That would cause the least upset if one forgot to declare an accessor type.
Reply:fields are private by default, but it's good practice to give them a type.


No comments:

Post a Comment