Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 314
Larry Avatar asked Feb 24 '23 13:02

Larry


2 Answers

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.

like image 142
Chris Jester-Young Avatar answered Mar 05 '23 20:03

Chris Jester-Young


It's a basic feature of any OOP language. That's why all deconstructors in C++ should be virtual - to implement polymorphism. To make the appropriate method be called. This is a good artical to understand how it works

like image 28
Fedor Skrynnikov Avatar answered Mar 05 '23 20:03

Fedor Skrynnikov