Method overloading and method overriding are two different concepts in Java that involve the use of methods in classes.
Method Overloading: - Method overloading refers to defining multiple methods in a class with the same name but with different parameters. - The methods must have different parameter types or a different number of parameters. - Method overloading is resolved at compile time and is known as compile-time polymorphism. - The return type can be the same or different for overloaded methods.
Example of method overloading:
public class Example { public int add(int a, int b) { return a + b; } public double add(double a, double b) { return a + b; } }
Method Overriding: - Method overriding refers to defining a method in a subclass that has the same signature (method name, parameter types, and return type) as a method in the superclass. - The overriding method must override the superclass method, providing its own implementation. - Method overriding is resolved at runtime and is known as runtime polymorphism. - The return type and method name must be the same for overridden methods.
Example of method overriding:
public class Animal { public void makeSound() { System.out.println("Animal makes a sound"); } } public class Dog extends Animal { @Override public void makeSound() { System.out.println("Dog barks"); } }
In summary, method overloading is related to the same class having multiple methods with the same name but different parameters, while method overriding is related to a subclass providing a specific implementation for a method that is already defined in its superclass.
Visit https://www.iteducationcentre.com/java-training-classes-in-pune.php for more details