5

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?

4 Answers 4

7

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

1

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.