Can you access a private variable from the superclass using the super keyword within the subclass? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Can you access a private variable from the superclass using the super keyword within the subclass?

6th Dec 2016, 3:03 PM
Elizabeth Brown
2 Answers
+ 1
No. Private variables are only accessible to the class members where it belongs. protected variables can be accessed from base class.
6th Dec 2016, 3:59 PM
Nikunj Arora
Nikunj Arora - avatar
0
When you inheritance other class, you cannot access your private attributes directly. So, if you have a class named "A" and other called "B", and make B extends A, B cannot access private attributes of A. Think this like a protection. This way, you can write some attributes in class "A" that you dont want others classes access it through inheritance. The "B" class can access only public, protected and default attributes directly in "A" class. But if you want to access a private attribute in "A" class for any reasons, you can write a m public class A{ private int foo; public int getFoo(){ return this.foo; } } public class B extends A{ public void doSomething(){ getFoo(); //return the private foo attribute of superclass } }
6th Dec 2016, 4:08 PM
Vipul Walia
Vipul Walia - avatar