W
W
WTFAYD2016-07-12 18:54:29
Java
WTFAYD, 2016-07-12 18:54:29

How to answer a question about polymorphism in Java?

Hello!
The task is:
Create a base class with two methods. In the first method, call the second method. Inherit a class and override the second method. Create an object of the derived class, upcast it to the base type, and call the first method. Explain what happens.
There is a code:

import static net.mindview.util.Print.*;

class A {
    void a() {
        b();
    }
    void b() {
       print("A.b()");
    }
}

class B extends A {
    @Override void b() {
        print("B.b()");
    }
}

public class Program {
    static public void main(String[] args) {
        A aa = new B();
        aa.a();
    }
}

Conclusion:
Bb()

How to explain what happened in the end? There was an upcast to the base class, a call to the a() method of the base class, and, within that method, an overridden b() method - am I right?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Cheremisin, 2016-07-12
@WTFAYD

Maybe it will be easier?
Class B inherits the methods and variables of class A. And when we call the method of object B, then it can use the methods and variables of object A, you can also represent object B as object A, but the behavior will be the same as that of object B.
In my example, the overridden method b of class B was called, followed by a call to the parent original method of class A. Moreover, it is clear that the forced castation (casting) of class B to class A does not change anything, as the object of class B was, it remained the same, with the overridden method.
And yet, an object is usually called an instance of a class, something that was formed after new.

package jtests;
import java.lang.System;

public class MyTest {

  class A {
    String  a () {
      return("from A:a");
    }
    String b() {		
      return("from A:b - " + a());
    }
    
  }
  class B extends A {
    @Override String b() {
      return ("from B:b - " + super.b());
    }
  }
  
  public static void main(String[] args) {
    MyTest m = new MyTest();
        
    System.out.println("A");
    A a =  m.new A(); // Используем A
    System.out.println(a.getClass().getName() + " * " + a.b());
    
    System.out.println("B");
    B b =  m.new B(); // Используем B
    System.out.println(b.getClass().getName() + " * " + b.b());
    
    System.out.println("B -> A");		
    A ab = (A) m.new B(); // Используем B как A
    System.out.println(ab.getClass().getName() + " * " + ab.b());
  }
}

And Conclusion:
A
jtests.MyTest$A * from A:b - from A:a
B
jtests.MyTest$B * from B:b - from A:b - from A:a
B -> A
jtests.MyTest$B * from B:b - from A:b - from A:a

S
Sanan Yuzb, 2016-07-12
@Sanan07

In Java, methods are called on the type of the object, and since the second method was overridden, then it was called.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question