Question:
Did you override the method after performing an upward conversion from a derived class to a base class? Why didn't the nasvai() method of the base class get called?
class BasicClass {
void nasvai() { System.out.println("Basic_Nasvai"); }
}
class SubBasic extends BasicClass {
@Override
void nasvai() { System.out.println("Nasvai"); }
}
class P231Exc20 {
public static void main (String[] args) {
SubBasic sb = new SubBasic();
sb.nasvai();
BasicClass bc = sb;
bc.nasvai();
}
}
Conclusion:
Nasvai
Nasvai
Answer:
And he shouldn't have changed. In Java (unlike C++, for example), all functions are made virtual (virtual) and to find the function to be called, a special table (VMT) is used, which (simplified) assigns each object, when created, its type (by constructor ). And proceeding from type causes the necessary function. When converting a type, a record is saved in the VMT and, accordingly, the function is called based on the type of the created object and not on the variable associated with it.