Method superscript applies to all class hierarchy?

Asked

Viewed 100 times

0

When there are several extends (as in the example below) all methods are overwritten to the last extends? If not, which method will be used?

class D extends C {
  void x() {
    System.out.println(1);
  }

}
class C extends B {
  void x() {
    System.out.println(2);
  }

}
class B {
  void x() {
    System.out.println(3);
  }
  void y(B b) {
    b.x();

  }
  void y(C c) {
    c.x();

  }
  void y(D d) {
    d.x();

  }

}
class A {
  public static void main(String[] args) {
    new B().y(new C());

  }

}

1 answer

5


I do not know if I understand what you want to know, but I already say that no class is overwritten, this is not a quality that classes have. Methods can be overwritten.

And yes, all traditional methods in Java that are virtual are superscripted no matter how deep the hierarchy is and they replace the mother class method, so this code will print 2.

And therefore the class that will be used is the one that is instantiated in a given location, the choice of classes is made by the programmer. At no time does this code occur polymorphism, so in this case also there is no choice of methods, is used the method of the classes being used pure and simple.

And the envelopes should ideally use the annotation @Override.

  • Vlw friend, it was very clear, I wrote wrong was really methods. To be sure if I understood, if by chance I wrote "new B(). x()" instead of "new B(). y(new C())" would perform the polymorphism and return "1"?

  • This code has no polymorphism anywhere, much less in this part, but would result in 1 in a simple and direct way.

  • has no superscript?

  • There is no polymorphism.

  • Blz vlw for all, helped me a lot, I need to try to understand better the term polymorphism.

  • That’s why I put a link in the answer.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.