Field inheritance on Java -


are fields inherited "one level up"?

by mean if have superclass class, has subclass, , superclass has field, class inherit , subclass won't. correct?

and if is, there way make subclass automatically inherit field superclass given that, understand it, there's no way inherit 2 classes @ once?

thank takes time answer. realize question may impractical , in reality you'd override field or something, i'm not trying specific, trying learn how java works. thank you.

here's code:

public class superclass {     protected int entero;      protected void method(){         entero=1;     }     public class subclass extends class {      public subclass(){}  }   public class class extends superclass {      public class(){}     }        public static void main(string[] args){     class object= new class();     subclass subobject= new subclass(); /*this error, why?*/          subobject.entero=2; /*this 1 fine*/         object.entero=2;         object.method();         system.out.println(object.entero);         } 

any class b extends class a, inherit a's fields. if class c extends b, c inherit non-private instance fields , methods a , b, ie transitivity holds.

if field private, 1 cannot directly change subclass; however, can around using setter/getter methods.

if field protected, subclass has direct access it.

edit 1:

in comment field protected, still can't access subclass. thing can think of have situation this:

class {    protected int x;  }  class b extends {    private int x;  }  class c extends b {    private int z = x; } 

this not work because declaring x again in b, hiding x field a. so, c sees x b's private variable x, not have access to.

edit 2: i'm not going remove above edit, because it's informative, posted code, it's because subclass not extend (this later fixed in edit).


Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -