У меня есть подкласс ScottishPerson
, который наследуется от класса 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);
}
}
Запустив код, это результат.
Madainn Mhath!
Alba Gu Brath!
A scottish name
MacDonald
Good Morning!
A british name
Madainn Mhath!
A british name
Вот где путаница. Преобразование ScottishPerson
в BritishPerson
изменяет имя переменной на имя, определенное в суперклассе. Методы и переменные, существующие только в подклассе, такие как warcry()
и clanName
, отбрасываются. Однако вызов метода salute()
для класса с повышением приведения по-прежнему возвращает строку на основе реализации подкласса.
Это потому, что когда я создал объект britishPerson
, я ТОЛЬКО инициализировал класс BritishPerson
, а когда я создал объект britishPersonUpcasted
, я создал как класс BritishPerson
, так и класс ScottishPerson
, что привело к постоянному переопределению метода salute()
?