javapolymorphismupcasting

Problem in upcasting in Java?


Could someone please explain why this happening:

class Apple {

   String type;

   setType(){
      System.out.println("inside apple class");
      this.type = "apple";
   }

}

class RedApple extends Apple {

    String type;

    setType() {
      System.out.println("inside red-apple class");
       this.type = "redapple";
    }
}

int main {

    RedApple red = new RedApple();
    Apple apple = (Apple) red;
    apple.setType();

}

But the output produced is:

"inside red-apple class”

Why does the .setType() method execute the sub-class method, and not the super-class method, even though I am up-casting, as can be seen?


Solution

  • That's because that's how polymorphism works in Java: it always uses the most-derived version of the method, which overrides other versions.

    The only way to get the base-class version is to use super.setType within the most-derived override.