Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
316 views
in Technique[技术] by (71.8m points)

JAVA Protected variable not allowed to be access though an object in child class of different 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? (Choose all that apply.)

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

Ref: SCJP 1.6 Kathy_Sierra: As per Book Answer is C, D, E

Why NOT 'F'? can anybody please explain

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Counting them down I assume that line 9 is supposed to be this line:

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

Protected variables are accessible to subclasses. Fiz is a subclass of Foo so it can access b. It can do so in a static context.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...