Overriding − If super class and subclass have methods with same name including parameters. JVM calls the respective method based on the object used to call the method.
i.e. if the current object using which the method is called, is of super class type the method of the super class is executed.
Or, if the object is of the type subclass then the method of the super class is executed.
class SuperClass{ public static void sample(){ System.out.println("Method of the super class"); } } public class RuntimePolymorphism extends SuperClass { public static void sample(){ System.out.println("Method of the sub class"); } public static void main(String args[]){ SuperClass obj1 = new RuntimePolymorphism(); RuntimePolymorphism obj2 = new RuntimePolymorphism(); obj1.sample(); obj2.sample(); } }
Method of the super class Method of the sub class
Overloading − If a class have two or more methods with the same name and different parameters. JVM calls the respective method based on the parameters passed to it, at the time of method call.
public class OverloadingExample { public void display(){ System.out.println("Display method"); } public void display(int a){ System.out.println("Display method "+a); } public static void main(String args[]){ OverloadingExample obj = new OverloadingExample(); obj.display(); obj.display(20); } }
Display method Display method 20