I have a super class “Sam” and a sub-class “SubSam”
public class Sam {
String msg;
String msg1;
Sam(String mm, String mm1) {
msg = mm;
msg1 = mm1;
}
@Override
public String toString() {
return this.msg + " " + this.msg1;
}
}
class SubSam extends Sam {
String msg1="C";
public static void main(String[] args) throws Exception {
SubSam obj = new SubSam();
System.out.println(obj);
}
SubSam() {
super("A", "B");
}
}
The output is:
A B
Why “toString()” is referring the instance fields of “Sam” instead of “SubSam”. The output should be: A C
I am thinking over it for a long time now, but not getting?
Because instance variables in Java aren’t overridden, quite simply. A subclass can define a variable with the same name as one defined in one of its superclasses, but it counts as a separate variable for all intents and purposes.
For example, consider the following code:
Given those definitions, instances of
Bwill have two variables, one being of typeString, the other of typeint, but both will be namedvar. They are still separate variables which can be independently assigned to and read from, and Java does not consider there being anything wrong with this.If you want to override behavior as you indicate you want, you need to use methods instead. For instance, you could do it like this:
Now, if you call
System.out.println(new B());, it will printA C.