I am unable to understand upcasting and the accessing of methods. I have read through multiple other questions on a similar understanding problem I am having but I still can not understand. I am hoping that a more personalized answer to my question could help me understand it better.
My problem with upcasting is that I've learned from my computer science class that when an child object is upcasted to an parent class it just is labeled something else, because it is labeled something else it is unable to call methods from the child class.
This is there explanation: "Cats can’t purr, while being labeled something else If you upcast an object it will lose all its properties which were inherited from below its current position. For example, if you cast a Cat to an Animal, it will lose properties inherited from Mammal and Cat. Note, that data will not be lost you just can't use it until you downcast the object to the right level. Why is it like that? If you have a group of Animals, then you can't be sure which ones can meow() and which ones can bark(). That is why you can't make Animal do things that are only specific for Dogs or Cats."
This explanation makes sense to me but when I tested it in this code:
public class SchoolMember
{
public void schoolDay()
{
System.out.print(“School open”);
}
}
public class Teacher extends SchoolMember
{
public void schoolDay()
{
System.out.print(“Teachers teaching”);
}
}
public class TeacherAide extends Teacher
{
public void schoolDay()
{
System.out.print(“Students learning”);
}
}
public class Main(){
public static void main(String[] args){
SchoolMember person1 = new SchoolMember();
Teacher person2 = new Teacher();
TeacherAide person3 = new TeacherAide();
person2 = (Teacher) person3;
person1.schoolDay();
person2.schoolDay();
}
}
The output of this code is: Schools OpenStudentsLearning
but from my understanding the output of the code should be Schools OpenTeachers teaching
Could somebody please help me with understanding this question.