JAVA protected variable is not allowed to access, although an object in a child class of another package

Given two files:

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

1  package pkgB;
2  import pkgA.*;
3  public class Fiz extends Foo {
4     public static void main(String[] args) {
5        Foo f = new Foo();
6        System.out.print(" " + f.a);
7        System.out.print(" " + f.b);
8        System.out.print(" " + new Fiz().a);
9        System.out.println(" " + new Fiz().b);
10    }
11  }

What is the result? (Select all that apply.)

a. 5 6 5 6
B. 5 6 followed by an exception C. Compilation error with an error in line 6
D. Compilation error with an error in line 7
E. Compilation error with an error in line 8
F. Compilation failed with error on line 9

Ref: SCJP 1.6 Kathy_Sierra: According to the answer to the book: C, D, E

Why NOT 'F'? can someone explain

-3
source share
2 answers

Having counted them, I assume that line 9 should be like this:

System.out.println(" " + new Fiz().b);

. Fiz Foo, b. .

0

protected Java. , "" , .

, Child Parent, Parent . , Child, - Child, Parent. , ?

Core Java 9th Edition:

Manager leaseDay , Employee. ,

(class Manager extends Employee, Employee hireDay)

,

public class Manager extends Employee {
    // accessing protected member of itself
    public void foo1() {   
        System.out.println("" + this.hireDay);  // OK
    }

    // access protected member of instance of same type
    public void foo2(Manager manager) {  
        System.out.println("" + manager.hireDay);  // OK
    }

    // access protected member of instance of super-class
    public void foo3(Employee employee) {
        System.out.println("" + employee.hireDay);  // NOT ALLOWED!
    }
}
0

Source: https://habr.com/ru/post/1529738/


All Articles