开发者

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 th开发者_C百科e .setType() method execute the sub-class method, and not the super-class method, even though I am up-casting, as can be seen?


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.


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


This is polymorphism, you have overridden the method so now whenever you call that method on that object, even if it's cast to a super class, the child-most method will be called.

However, an example of where the upcasting DOES make a difference is here:

class MyClass {
    static void doSomething(Apple apple) { System.out.println("Apple"); }
    static void doSomething(RedApple apple) { System.out.println("RedApple"); }
}
...
RedApple apple = new RedApple();
MyClass.doSomething(apple);
MyClass.doSomething((Apple)apple);

Output:

RedApple
Apple

Since we upcast it to an Apple the best matched method is the one with the Apple parameter.


This the how java has been designed to work, which is called Overriding behavior of methods. If you want to have the method in the super class, you can use method-hiding i:e static methods both in parent and child class with same signature.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜