2
//Filename: A.java
package packageA;
public class A {
    protected int x;
}

//Filename B.java
package packageB;
import packageA.A;

public class B extends A {
    void action(A ob1, B ob2, C ob3) {
        x = 10;
        ob1.x = 10;   // <-- error here
        ob2.x = 10;
        ob3.x = 10;
    }

public class C extends B {
    void action(A ob1, B ob2, C ob3) {
        x = 10;
        ob1.x = 10;    // <-- error here
        ob2.x = 10;    // <-- error here
        ob3.x = 10;
    }

So, I was reading protected usage in Java and came across this problem. A.java and B.java are separate files and kept in separate packages as you can see. While compiling B.java, I get 3 ERRORS that x has protected access in A. Can somebody explain why I'm getting error even after extending class A?

hata
  • 11,633
  • 6
  • 46
  • 69
fireboy91
  • 113
  • 8

2 Answers2

1

You're not allowed to access a protected member through the supertype reference. See Java Language Specification, section 6.6.2: Details on Protected Access.

A compile-time error occurs in the method delta here: it cannot access the protected members x and y of its parameter p, because while Point3d (the class in which the references to fields x and y occur) is a subclass of Point (the class in which x and y are declared), it is not involved in the implementation of a Point (the type of the parameter p). The method delta3d can access the protected members of its parameter q, because the class Point3d is a subclass of Point and is involved in the implementation of a Point3d.

sh0rug0ru
  • 1,596
  • 9
  • 9
0

In method action of class B, you get an instance of class A -- ob1 as an argument.

The ob1 itself is a pure class A object. It is not a instance of class B which extended from class A. So, you can't override protected member of class A outside of class A.

You can override a field member x of class B because the x is extended from class A's protected member x.

public class B extends A {

    // class B has member x in field which is extended from class A

    void action(A ob1, B ob2, C ob3) {
        x = 10;     // <-- this is extended field member x from class A in class B
        ob1.x = 10; // <-- this is protected member of other instance of A
        ob2.x = 10;
        ob3.x = 10;
    }
}
hata
  • 11,633
  • 6
  • 46
  • 69