Problem raising tariffs in Java?

Could you explain why this is 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 result is:

 "inside red-apple class" 

Why is the .setType() method executing a subclass method and not a superclass method, even though I am raising up, as you can see?

+4
source share
4 answers

This is because how polymorphism works in Java: it always uses the most derived version of a method that overrides other versions. The only way to get the base class version is to use super.setType in the derived override itself.

+5
source

This is the main feature of any OOP language. That's why all deconstructors in C ++ must be virtual - to implement polymorphism. To call the appropriate method. It is a good artistic to understand how it works.

+2
source

This is polymorphism, you have now redefined the method, when you call this method on this object, even if it is applied to the superclass, the child-most method is called.

However, an example of where the increase occurs matters:

 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 upgrade it to Apple, the best matching method is the one that has the Apple parameter.

+1
source

This is how Java was designed to work, which is called method behavior overriding. If you want to have a method in a superclass, you can use the i: e method of hiding static methods in both the parent and child class with the same signature.

0
source

All Articles