accessing fields across a package
Ho开发者_开发知识库w 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.
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.
package pkg;
public class One {
public int fieldOne;
}
package pkg;
public class Two {
private One one;
public int getOne() {
return one.fieldOne;
}
}
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:
public class A {
public int counter;
private int counter2;
public int getCounter2() { return counter2; }
public void setCounter2(int c) { counter2 = c; }
}
public class B extends A {
public void setCounter2(int c) {
if (c < 0) throw new IllegalArgumentException("counter2 cannot be negative");
super.setCounter2(c);
}
}
Compare the way that the counter
and counter2
attributes behave. In the case of counter
, any code in any class can read or update the attribute without restriction. This applies both for instances of the class A
and any classes that extend A
. If some other class decides to set counter
to a bad value ... there's nothing to prevent it.
In the case of counter2
, the attribute of an instance of A
can only be read or updated by the getCounter2
and setCounter2
methods respectively. If I want to, I can change these methods in A
to do validation, perform access checks, notify some listener of a state change an so on. And because this behavior can only occur in methods of A
, 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 as private
, the setCounter2
method in B still has to call the method in its superclass. And that's good too.
The following code should compile. Class Two has access to the field in class One. Please check your own if there is a difference.
package one;
public class A {
public int fieldA;
}
package two;
import one.A;
public class B {
private A a;
public int getA() {
return a.fieldA;
}
}
精彩评论