Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

protected access type [duplicate]

Possible Duplicate:
In Java, what's the difference between public, default, protected, and private?

Why can't a subclass in one package access the protected member of it's superclass (in another package) by the reference of the superclass? I am struggling with this point. Please help me

package points;
public class Point {
  protected int x, y;
}

package threePoint;
import points.Point;
public class Point3d extends Point {
  protected int z;
  public void delta(Point p) {

    p.x += this.x;          // compile-time error: cannot access p.x
    p.y += this.y;          // compile-time error: cannot access p.y

  }
like image 806
vijay Avatar asked Jun 06 '26 08:06

vijay


1 Answers

A protected member can be accessed by the class, other classes in the package and implicitly by its subclasses. i.e., the subclass can access x from its own parent.

The fact that you are able to access this.x proves that x from the superclass is accessible. If x were private in the superclass, this.x would give an error.

When you say p.x you are trying to access some other instance's x, and not in its own hierarchy. This is not allowed outside the package.

like image 106
Nivas Avatar answered Jun 07 '26 22:06

Nivas