I have a superclass and I want to use a variable that is inside this superclass into my subclass. How can this be possible?
You can try to convert the super class variable to the sub class type by simply using the cast operator. But, first of all you need to create the super class reference using the sub class object and then, convert this (super) reference type to sub class type using the cast operator.
Rule:A subclass inherits all of the member variables within its superclass that are accessible to that subclass (unless the member variable is hidden by the subclass). inherit those member variables declared with no access specifier as long as the subclass is in the same package as the superclass.
First approach (Referencing using Superclass reference): A reference variable of a superclass can be used to a refer any subclass object derived from that superclass. If the methods are present in SuperClass, but overridden by SubClass, it will be the overridden method that will be executed.
A subclass does not inherit the private members of its parent class. However, if the superclass has public or protected methods for accessing its private fields, these can also be used by the subclass. A nested class has access to all the private members of its enclosing class—both fields and methods.
Just make the field protected
, meaning that it should be visible to all derived classes.
I have a superclass and I want to use a variable that is inside this superclass into my subclass. How can this be possible?
If your variable is declared as protected
or public
(or) your variable hasdefault
access privileges(in which case you don't specify with any keyword) and they are in same package(--> You can access it in the subclass directly.
You may use this
keyword if you are specific.
Example:
public class A{
protected int field=1;
}
public class B extends A{
public B(){
System.out.println(this.field);
}
public static void main(String args[]){
new B();
}
}
Please note that variable-overriding is not possible. If you have a variable with the same name as in super class then you are out of luck to directly access it. Then you may use super
keyword.
public class A{
protected int field=1;
}
public class B extends A{
protected int field=3;
public B(){
System.out.println(this.field);
System.out.println(super.field);
}
public static void main(String args[]){
new B();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With