/**
* Class that demonstrates Overloading of methods. myMethod() has been overloaded three
* times...
*/
public class OverloadExample {
public void myMethod() {
System.out.println("Blank");
}
public void myMethod(String str) {
System.out.println("Input is: " + str);
}
public void myMethod(int arg) {
System.out.println("Value is: " + arg);
}
public void myMethod(double arg) {
System.out.println("Value is: " + arg);
}
public static void main(String[] args) {
OverloadExample example = new OverloadExample();
example.myMethod();
example.myMethod("Hello");
example.myMethod(42);
example.myMethod(23.3);
}
}
The code above demonstrates overloading, whilst the code below demonstrates overriding:
/**
* Class that demonstrates Overriding of methods. myMethod() has been overridden twice...
*/
public class OverrideExample extends OverloadExample {
@Override
public void myMethod(String str) {
System.out.println("New input is: " + str);
}
@Override
public void myMethod(int arg) {
System.out.println("New value is: " + arg);
}
public static void main(String[] args) {
OverrideExample example = new OverrideExample();
example.myMethod();
example.myMethod("Hello");
example.myMethod(42);
example.myMethod(23.3);
}
}
The only tip here is to read the question carefully: overloading is not overriding they just sound similar.
2 comments:
Thanks a bunch...simple,precise understandable explanation!!!
Indeed very good blog, clean and precise.By the way I have also shared some rules of method overloading and overriding in Java, which complements your blog post.
Thanks
Javin
Post a comment