8.2.1
Examples of Inheritance
CLASSES
8.2.1.4
Accessing Members of Inaccessible Classes
Even though a class might not be declared
public
, instances of the class might be
available at run time to code outside the package in which it is declared if it has a
public
 superclass or superinterface. An instance of the class can be assigned to a
variable of such a
public
 type. An invocation of a
public
 method of the object
referred to by such a variable may invoke a method of the class if it implements or
overrides a method of the
public
 superclass or superinterface. (In this situation,
the method is necessarily declared
public
, even though it is declared in a class
that is not
public
.)
Consider the compilation unit:
package points;
public class Point {
public int x, y;
public void move(int dx, int dy) {
x += dx; y += dy;
}
}
and another compilation unit of another package:
package morePoints;
class Point3d extends points.Point {
public int z;
public void move(int dx, int dy, int dz) {
super.move(dx, dy); z += dz;
}
}
public class OnePoint {
static points.Point getOne() { return new Point3d(); }
}
An invocation
morePoints.OnePoint.getOne()
 in yet a third package would
return a
Point3d
 that can be used as a
Point
, even though the type
Point3d
 is
not available outside the package
morePoints
. The method
move
 could then be
invoked for that object, which is permissible because method
move
 of
Point3d
 is
public
 (as it must be, for any method that overrides a
public
 method must itself
be
public
, precisely so that situations such as this will work out correctly). The
fields
x
 and
y
 of that object could also be accessed from such a third package.
While the field
z
 of class
Point3d
 is
public
, it is not possible to access this
field from code outside the package
morePoints
, given only a reference to an
instance of class
Point3d
 in a variable
p
 of type
Point
. This is because the
expression
p.z
 is not correct, as
p
 has type
Point
 and class
Point
 has no field
named
z
; also, the expression
((Point3d)p).z
 is not correct, because the class
142






footer




 

 

 

 

 Home | About Us | Network | Services | Support | FAQ | Control Panel | Order Online | Sitemap | Contact

java hosting

 

Our partners: PHP: Hypertext Preprocessor Best Web Hosting Java Web Hosting Inexpensive Web Hosting  Jsp Web Hosting

Cheapest Web Hosting Jsp Hosting Cheap Hosting

Visionwebhosting.net Business web hosting division of Web Design Plus. All rights reserved