[JAVA] Overload when method arguments are inherited / implemented

In Java, when overriding a class that has an inheritance / implementation relationship, the type is determined at runtime and the method is called, but in the overload, I tried to find out which method is called.

interface

public interface OInterface {
	public void printClassname();
}

** Parent class **

public class OParent  {
	public void printClassname() {
		System.out.println("called:OParent=>printClassname()");
	}
}

** Child class (implementing interface) **

public class OChild extends OParent implements OInterface {

	@Override
	public void printClassname() {
		System.out.println("called:OChild=>printClassname()");
	}
}

** Execution code **

public class OverloadMain {
	public static void main(String[] args) {

		OverloadMain main = new OverloadMain();

		OChild child = new OChild();
		OParent parent = new OChild();
		OInterface iface = new OChild();

		main.overloadMethod(child);  // (1)
		System.out.println("----");
		main.overloadMethod(parent); // (2)
		System.out.println("----");
		main.overloadMethod(iface);  // (3)
	}


	public void overloadMethod(OChild child) {
		System.out.println("called:overloadMethod(OChild)");
		child.printClassname();
	}

	public void overloadMethod(OParent parent) {
		System.out.println("called:overloadMethod(OParent)");
		parent.printClassname();
	}

	public  void overloadMethod(OInterface iface) {
		System.out.println("called:overloadMethod(OInterface)");
		iface.printClassname();
	}
}

** Forecast ** Prediction 1. All (1) to (3) are called overrideMethod (OChild child) (same as override) Prediction 2. In (1) to (3), the method of the declared type is called.

Execution result

called:overloadMethod(OChild)
called:OChild=>printClassname()
----
called:overloadMethod(OParent)
called:OChild=>printClassname()
----
called:overloadMethod(OInterface)
called:OChild=>printClassname()

Conclusion

Prediction 2. In (1) to (3), the method of the declared type is called. was The overload is decided at compile time, isn't it?

Recommended Posts

Overload when method arguments are inherited / implemented
Overload method with Int and Integer arguments
About characters that are completed in method arguments
Ruby Hash stack overflows when there are many arguments