How do I make fields accessible across a package? Currently, even if they are declared public i’m not able to access the fields from another class in the same package.
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Here’s a more apposite example. (Based on @Andreas_D’s example … as if it ain’t obvious!)
Note that an import is not needed to refer to a class declared in the same package.
Having said this, referring to public attributes declared in another class is generally a bad idea. It is better to declare the attributes as private and access them via getter and setter methods. (If the attributes are exposed as public and they are not final, that anything can modify them. Furthermore, there is no way that a subclass can hide the attributes, or change the way that they behave.)
EDIT
To illustrate the last point:
Compare the way that the
counterandcounter2attributes behave. In the case ofcounter, any code in any class can read or update the attribute without restriction. This applies both for instances of the classAand any classes that extendA. If some other class decides to setcounterto a bad value … there’s nothing to prevent it.In the case of
counter2, the attribute of an instance ofAcan only be read or updated by thegetCounter2andsetCounter2methods respectively. If I want to, I can change these methods inAto do validation, perform access checks, notify some listener of a state change an so on. And because this behavior can only occur in methods ofA, I know where to start looking in the event of something strange happening.If I define a subclass of
A(e.g.B), I can override either or both of the methods to do something different. But note that since I decided to declare the actual attribute asprivate, thesetCounter2method in B still has to call the method in its superclass. And that’s good too.