I have 2 classes A and B such that
public class A {
public String a = "hey";
public void printA() {
System.out.println(a);
}
and
public class B extends A{
public String a = "Jude";
}
What do I need to do so that the output of the lines below is Jude
B object = new B();
object.printA(); //This should output Jude
You cannot access the subclass field from the superclass. However you can change it in subclass like this:
This way you don't declare the new field, but change the value of existing one. Note that
extends A
is necessary to specify thatB
is subclass ofA
.Alternatively you may consider using a method instead of field:
Note that in Java "variable" term usually applied to local variables declared within methods. You are speaking about "field", not "variable".