Why this code is wrong and Java in a Nutshell said so? -
i read java in nutshell now, , met question java in nutshell. example come book. see: e.g.:
package de; public class { protected string x; } package uk; import de.*; class b extends { //first 1 public string getx(a a) { return "getx works" + a.x;//error: x has protected access in } //second 1 public string getx(b b) { return "getx works" + b.x; // works! } }
the author means because instances of b not have access arbitary instances of a. , if change code second one, compiler happy, because instances of same exact type can see each other’s protected fields. can not understand author's meaning, actually?
b extends a. x protected in a. b can access x's in b's.
b can not access x's in a's (that not b's).
consider class c extends a.
can see reasoning (objecte oriented principle) behind b's can't access c's x's.
Comments
Post a Comment