java - Why isn't protected field visible to a subclass? -


i have class:

package foo; public abstract class abstractclause<t>{     protected t item;     protected abstractclause<t> next; } 

and subclass (in different package):

package bar; import foo.abstractclause;  public class concreteclause extends abstractclause<string>{      public void somemethod(concreteclause c) {         system.out.println(this.next);      // works fine         system.out.println(c.next);         // works fine         system.out.println(this.next.next); // error: next not visible     } } 

why?

it seems if subclass in different package, methods can access own protected instance fields, not of other instances of same class. hence this.last , this.next work because access fields of this object, this.last.next , this.next.last not work.

public void append(restrictionclauseitem item) {     abstractclause<concrete> c = this.last.next; //error: next not visible     abstractclause<concrete> d = this.next; //next visible!     //some other staff } 

edit - wasn't quite right. upvotes anyway :)

i tried experiment. have class:

public class vehicle {     protected int numberofwheels; } 

and 1 in different package:

public class car extends vehicle {    public void method(car othercar, vehicle othervehicle) {     system.out.println(this.numberofwheels);     system.out.println(othercar.numberofwheels);     system.out.println(othervehicle.numberofwheels); //error here!   } } 

so, it's not this important thing. can access protected fields of other objects of same class, not protected fields of objects of supertype, since reference of supertype can hold object, not necessary subtype of car (like bike) , car can't access protected fields inherited different type vehicle (they accessible extending class , subtypes).


Comments

Popular posts from this blog

powershell Start-Process exit code -1073741502 when used with Credential from a windows service environment -

twig - Using Twigbridge in a Laravel 5.1 Package -

c# - LINQ join Entities from HashSet's, Join vs Dictionary vs HashSet performance -