Java Multilevel Inheritance - Protected Instance Variable in Level 1 Class
Solution 1
variable/methods marked with protected
modifier are visible to all the classes in the same pacakage and only to subclasses in different packages.
below are the example cases.
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
}
Solution 2
The access level modifiers in Java are:
-
public
- visible to all code -
protected
- visible to all code in the same package and to subclasses regardless of package - nothing (default) - visible to all code in the same package
-
private
- visible only to code in the same class (including nested classes)
See, for instance, the Java tutorial Controlling Access to Members of a Class or (for lots of technical details) section 6.6 of the Java Language Specification.
Solution 3
Definition of the keyword
Protected
The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package.
I suggest you read this.
Solution 4
The Java protected
keyword works its way down to all subclasses (and members of the package). If there was a protected
member in Object
, any object could access it. By contrast, private
is only visible to the local class (and inner classes), and public
is accessible by all.
Have a look at this glossary, which shows in-depth how protected
members and methods are inherited, and the Java documentation on inheritance.
Solution 5
Please refer this: http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package.
So if your class C
shares the package with A
and B
, its accessible.
Dhruvenkumar Shah
Updated on June 04, 2022Comments
-
Dhruvenkumar Shah almost 2 years
I have an question which comes under multilevel inheritance in Java. All Three Classes are in 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 like have any significance? or it is behavior which we have to take it by default?