Java multi-level inheritance – protected instance variables in level 1 classes

I have a problem with multi - level inheritance in Java All three classes are in the same package

I have class A:

public class A {
   protected int x;
}

public class B extends A {
   public void doSomething {
      // x is visible.agreed,as it is a direct subclass of A
   }  
}


public class C extends B {
   public void doSomething {
      // x is still visible,how come? I mean it is at the 2nd level 
     //  I am confused why?
   }  
}

Does it mean anything? Or what we have to do by default?

Solution

Variables / methods marked as protected modifier are visible to all classes in the same package and only to subclasses in different packages

package a;
class A{
protected int x;
}
class B extends A{
//x can be accessed from this class
} 

class C extends B {
//x can be accessed from this class
}
class D{
//x can be accesed this class but you will have to create A's instance 
}

package B 
class One {
//cannot access x from this class
}
class Two extends A {
//can access x from this class
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>