What it is: a class has several methods with the same name but different number or types of parameters and Java chooses which one to call based on the arguments you pass
classOverloadingTest{
publicvoidtestMethod(Object object){
System.out.println("object");
}
publicvoidtestMethod(String string){
System.out.println("string");
}
}
OverloadingTest test =newOverloadingTest();
Object testObject =newObject();
String testString ="testString";
test.testMethod(testObject);// object
test.testMethod(testString);// string
Important: the exact signature of the method to call is based at compile time using the compile-time types of the arguments
What it is: a subclass overrides an instance method of a direct or indirect superclass by providing its own implementation
classOverridingTestSuper{
publicvoidtestMethod(Object object){
System.out.println("super");
}
}
classOverridingTestSubextendsOverridingTestSuper{
@Override
publicvoidtestMethod(Object object){
System.out.println("sub");
}
}
Note: use@Override annotation when overriding, so the Java compiler helps you check that the method is actually correctly overriding a supertype method
Important: The implementation to invoke is determined at run time based on the actual runtime type of the object and the structure of the inheritance hierarchy
For static methods, overloading is still used to determine the signature of the method to invoke
But what if superclass and subclass both have static method with same signature?
classCombinedTestSuper{
publicstaticvoidtestStaticMethod(Object object){
System.out.println("super");
}
}
classCombinedTestSubextendsCombinedTestSuper{
publicstaticvoidtestStaticMethod(Object object){
System.out.println("sub");
}
}
Calling static methods on classes:
Object testObject =newObject();
StaticSuper.testStaticMethod(testObject);// super
StaticSub.testStaticMethod(testObject);// sub
Calling static methods on instances (note that this will generate compiler warnings):
StaticSuper staticSuper =newStaticSuper();
StaticSub staticSub =newStaticSub();
StaticSuper staticSubAsSuper = staticSub;
staticSuper.testStaticMethod(testObject);// super
staticSub.testStaticMethod(testObject);// sub
staticSubAsSuper.testStaticMethod(testObject);// super (!!!)
No overriding here! Instead, we get method hiding.
Can be pretty confusing (not only the method hiding itself, but also the fact that we call a static method in a way that makes it look like an instance method), which is also why we get warnings when doing this.