Method Overloading and Method Overriding - Copy
Method Overloading and Method Overriding - Copy
Static binding is being used for Dynamic binding is being used for
overloaded methods. overriding methods.
Private and final methods can be Private and final methods can’t be
overloaded. overridden.
The argument list should be different The argument list should be the same in
while doing method overloading. method overriding.
• class MethodOverloadingEx {
• static int add(int a, int b) { return a + b; }
• static int add(int a, int b, int c)
• {
• return a + b + c;
• }
• // Main Function
• public static void main(String args[])
• {
• System.out.println("add with 2 parameters");
• // Calling function with 2 parameters
• System.out.println(add(4, 6));
• System.out.println("add with 3 parameters");
• // Calling function with 3 Parameters
• System.out.println(add(4, 6, 7));
• }
• }
• // Method overriding Base Class
• class Animal {
• void eat() {
• System.out.println("eat() method of base class");
• System.out.println("Animal is eating.");
• }
• }
• // Derived Class
• class Dog extends Animal {
• @Override
• void eat() {
• System.out.println("eat() method of derived class");
• System.out.println("Dog is eating.");
• }
• // Method to call the base class method
• void eatAsAnimal() {
• super.eat();
• }
•}
• // Driver Class
• class MethodOverridingEx {
• // Main Function
• public static void main(String args[]) {
• Dog d1 = new Dog();
• Animal a1 = new Animal();
• // Calls the eat() method of Dog class
• d1.eat();
• // Calls the eat() method of Animal class
• a1.eat();
• // Polymorphism: Animal reference pointing to Dog object
• Animal animal = new Dog();
• // Calls the eat() method of Dog class
• animal.eat();
• // Polymorphism: Animal reference pointing to Dog object
• Animal animal = new Dog(); //
•
• // Calls the eat() method of Dog class
• animal.eat();
•
• // To call the base class method, you need to use a Dog reference
• ((Dog) animal).eatAsAnimal();
• }
•}
OUTPUT
• eat() method of derived class
• Dog is eating.
• eat() method of base class
• Animal is eating.
• eat() method of derived class
• Dog is eating.
• eat() method of base class
• Animal is eating.