This week's book giveaway is in the Design forum.
We're giving away four copies of Building Microservices and have Sam Newman on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Default access Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Building Microservices this week in the Design forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Default access" Watch "Default access" New topic

Default access

Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
Hi, have a look at the foll. code
package points;
public class Point {
int x, y;
public void move(int dx, int dy) { x += dx; y += dy; }//1
package points;
public class Point3d extends Point {
int z;
public void move(int dx, int dy, int dz) {
x += dx; y += dy; z += dz;
and a third compilation unit, in another package, is:
import points.Point3d;
class Point4d extends Point3d {
int w;
public void move(int dx, int dy, int dz, int dw) {
super.move(dx, dy, dz); w += dw;}}}
My doubt is at line 1 if public is replaced with default
then i get an error when compiling point 4d.Please explain
why is it so?

Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
hi avn,
default access means only classes in that package can acess the class. Packages in the simplest of terms are folders. Putting classes into packages prevent name conflicts.
public access means that any class in any package can access that class by importing the package.
Point3d is in your question is public and exists as a part of points package. as such any class including Point4d are able to acess it by importing the package.
Point4d is in the default package. It is not in the points package. Thus it can access classes in another package either by
1) Subclassing them ( the classes subclassed need to be protected or public )
2) Only if the classes are public
thus by changing the access specifiers to default you are voilating the first rule where in the subclassed class needs to be public or protected. Hence the result if u r changing Point3d to default access.
If u change the Point class to default access too the compiler will complain again. This is because when constructiong an object of Point4d the constructor of Point3d is called and the first statement executes super() which calls the constructor of Point class.
Since you are in another package and Point has default acess you cannot invoke the constructor of Point.
I hope i am clear.
[This message has been edited by rahul_mkar (edited July 27, 2000).]
Have you checked out Aspose?
subject: Default access
It's not a secret anymore!