0

The problem is about protected access. What is wrong with this code :

package pkgA; 
public class Foo { 
    protected int b = 6; 
} 

package pkgB; 
import pkgA.*; 

class Food extends Foo { 
    void met(){
        System.out.println(new Food().b);
    } 
}; 

public class Baz { 
    public static void main(String[] args) { 
        Food fd = new Food(); 
        fd.met();  // *line 1* 
        System.out.println(" " + fd.b); // *line 2*; error : b has          protected access in Foo 
    } 
} 

Why line 1 is good but line 2 not?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
user989093
  • 33
  • 2
  • Why do you think it _should_ work? Please explain your thinking – Boris the Spider Feb 18 '18 at 12:27
  • `met()` is a package-protected method, so accessible from `Baz` as it is apparently in the same package. `b` is protected, so accessible from `Food` as a subclass but not `Baz` as it is not a subclass. – lexicore Feb 18 '18 at 12:31

1 Answers1

0

You are trying to access b from Baz, which isn't possible, because b is protected. Only classes that derive from Foo can access b.

You can access met() because it has no access modifier, and hence it is accesible for classes within the same package (both Baz and Food are in the same package).

This is basic inheritence by the way. More info here: https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html.

Bart Friederichs
  • 33,050
  • 15
  • 95
  • 195
  • I don't understand, b is accessed by instance fd of class Food and Food extend Foo. Food is a subclass of Foo, b is accessed by inheritance. Why fd.met() can access b but fd.b not ? – user989093 Feb 18 '18 at 12:40
  • `Food` is in the same package as `Baz` and `met()` has no access modifier. – Bart Friederichs Feb 18 '18 at 12:42