I have a subclass ScottishPerson
which inherits from the class BritishPerson
.
class BritishPerson {
public String name = "A british name";
public void salute() {
System.out.println("Good Morning!");
}
}
class ScottishPerson extends BritishPerson {
public String name = "A scottish name "; //Variable overriding
public String clanName = "MacDonald";
public void salute() //Method overriding
{
System.out.println("Madainn Mhath!");
}
public void warcry() {
System.out.println("Alba Gu Brath!");
}
}
class Driver {
public static void main(String[] args) {
ScottishPerson scottishPerson = new ScottishPerson(); //Created as a subclass, can always be upcasted.
BritishPerson britishPerson = new BritishPerson(); //Created as the superclass, throws an error when downcasted.
BritishPerson britishPersonUpcasted =
new ScottishPerson(); //Created as the subclass but automatically upcasted, can be downcasted again.
//Checking the methods and parameters of scottishPerson
scottishPerson.salute();
scottishPerson.warcry();
System.out.println(scottishPerson.name);
System.out.println(scottishPerson.clanName);
//Checking the methods and parameters of britishPerson
britishPerson.salute();
System.out.println(britishPerson.name);
//Checking the methods and parameters of britishPersonUpcasted
britishPersonUpcasted.salute();
System.out.println(britishPersonUpcasted.name);
}
}
Running the code, this is the output.
Madainn Mhath!
Alba Gu Brath!
A scottish name
MacDonald
Good Morning!
A british name
Madainn Mhath!
A british name
This is where the confusion lies. Upcasting ScottishPerson
to BritishPerson
changes the variable name into the one defined un the superclass. Methods and variables that exist only in the subclass such as warcry()
and clanName
are discarded. However, calling method salute()
on the upcasted class still returns the string based on the subclass implementation.
Is it because when I created the object britishPerson
I ONLY initialize the BritishPerson
class, and that when I created the object britishPersonUpcasted
I created both the BritishPerson
class and ScottishPerson
class which lead to the permanent overriding of the salute()
method?