1

I'm in an AP Comp Sci class and the course instructor nor me or my classmates are having any luck understanding upcasting via polymorphism. We more or less understand what it's doing, but not particularly why. Here's some pseudo code as an example:

public class Student {

   public String getFood() {
      return "Pizza";
   }

   public String getInfo()  {
     return this.getFood();
   }

   public static void main(String[] args)
   {
     Student s1 = new GradStudent();
     System.out.print(s1.getInfo());
   }
}

class GradStudent extends Student {
  public String getFood() {
     return "Taco";
  }
}

So in this example, it's the upcast from GradStudent to Student that we don't understand. Basically, what's the reason we should use Student s1 = new GradStudent(); over GradStudent s1 = new GradStudent();? If anything, isn't it even more problematic to use the upcast, since that throws an error should a called method not exist within it's super class? Perhaps this is a poor example since in execution they seem to have the same output, but is there some fundamental difference in how execution is being ran?

0 Answers0