Java Reference
In-Depth Information
SubClass
Class
SubClass
No /
inhertited
int a;
int a;
public int b;
inhertited
public int b;
inhertited
public int b;
protected int c;
inhertited
inhertited
protected int c;
protected int c;
No/
private int w;
\No
Package2
Package1
Note that a class itself can be specified as public . This makes the class accessible
from any package anywhere. A class that is not declared as public can only be
accessed from classes within the same package. This means for instance that you
cannot define objects of a non- public class type within classes in other packages. It
also means that to derive a new class in a package that does not contain the base class,
the base class must be declared as public . If the base class is not declared as
public , it cannot be reached directly from outside the package.
As you can see, a subclass that you define in the same package as its base inherits everything except for
private data members of the base. If you define a subclass outside the package containing the base
class, the private data members are not inherited, and neither are any data members in the base class
that you have declared without access attributes. Members defined as private in the base class are
never inherited under any circumstances.
You should also be able to see where the explicit access specifiers now sit in relation to one another.
The public specifier is the least restrictive on class members since a public member is available
everywhere, protected comes next, and prevents access from classes outside of a package, but does
not limit inheritance - provided the class itself is public . Putting no access specifier on a class member
limits access to classes within the same package, and prevents inheritance in subclasses that are defined
in a different package. The most restrictive is private since access is constrained to the same class.
The inheritance rules apply to class variables - variables that you have declared as static - as well as
instance variables. You will recall that only one occurrence of each static variable exists, and is
shared by all objects of the class, whereas each object has its own set of instance variables. So for
example, a variable that you declare as private and static in the base class is not inherited in a
derived class, whereas a variable that you declare as protected and static will be inherited, and
will be shared between all objects of a derived class type, as well as objects of the base class type.
Search WWH ::




Custom Search