I have been doing some changes in my project where I found some weird or rather I will say unexpected behaviour of Polymorphism in Java. I have replicated same behaviour in a Poc given below.
1. CommonInterface.java
package com.general;
public interface CommonInterface {
public void getViews(String str);
public void getViews(String str, Long id);
}
2. GenericUtility.java
package com.general;
public class GenericUtility implements CommonInterface{
@Override
public void getViews(String str) {
System.out.println("This is getViews (single param)from GenericUtility");
getViews(str, null);
}
@Override
public void getViews(String str, Long id) {
System.out.println("This is getViews (multi-param) from GenericUtility");
}
}
3. CustomUtility.java
package com.general;
public class CustomUtility extends GenericUtility {
@Override
public void getViews(String str) {
System.out.println("This is getViews (single param)from CustomUtility");
super.getViews(str);
}
@Override
public void getViews(String str, Long id) {
System.out.println("This is getViews (multi-param) from CustomUtility");
super.getViews(str, null);
}
}
4. Main.java
package com.general;
public class Main {
public static void main(String[] args) {
GenericUtility utility = new CustomUtility();
String str = "Random String";
utility.getViews(str);
}
}
After running Main.java , my expected output is
This is getViews (single param)from CustomUtility
This is getViews (single param)from GenericUtility
This is getViews (multi-param) from GenericUtility
But output that I get is
This is getViews (single param)from CustomUtility
This is getViews (single param)from GenericUtility
This is getViews (multi-param) from CustomUtility
This is getViews (multi-param) from GenericUtility
I am not able to understand why com.general.GenericUtility#getViews(java.lang.String) is calling com.general.CustomUtility#getViews(java.lang.String, java.lang.Long)
Is this expected behaviour and what is it that I don't know ?
Thanks in advance.
utility.getViews(str)callsCustomUtility.getViews. Then you should also understand why the callgetViews(str, null);(equivalent tothis.getViews(str, null);) inGenericUtilitywill call the implementation inCustomUtility. The same rules apply, after all.