fbpx

Enroll Now

Java- Method Overloading and Overriding

Method Overloading

Method overloading in Java allows a class to have more than one method with the same name, as long as their parameter lists are different. Overloading is determined at compile-time and is a form of compile-time polymorphism.

Rules for Method Overloading:

  1. Methods must have the same name.
  2. Methods must have different parameter lists (different type, number, or both).
  3. It can have different return types.
  4. It can have different access modifiers.
class MathOperations {
    // Method to add two integers
    public int add(int a, int b) {
        return a + b;
    }

    // Overloaded method to add three integers
    public int add(int a, int b, int c) {
        return a + b + c;
    }

    // Overloaded method to add two doubles
    public double add(double a, double b) {
        return a + b;
    }
}

public class TestOverloading {
    public static void main(String[] args) {
        MathOperations math = new MathOperations();

        System.out.println("Sum of 2 and 3: " + math.add(2, 3));
        System.out.println("Sum of 2, 3, and 4: " + math.add(2, 3, 4));
        System.out.println("Sum of 2.5 and 3.5: " + math.add(2.5, 3.5));
    }
}

Explanation: In the MathOperations class, there are three overloaded add methods. The first method adds two integers, the second adds three integers, and the third adds two doubles. Depending on the arguments passed, the appropriate method is called at compile time.

Programming Examples for Method Overloading:

  1. Calculator with Overloaded Methods for Different Operations:
class Calculator {
    public int multiply(int a, int b) {
        return a * b;
    }

    public double multiply(double a, double b) {
        return a * b;
    }

    public int multiply(int a, int b, int c) {
        return a * b * c;
    }
}

public class TestCalculator {
    public static void main(String[] args) {
        Calculator calc = new Calculator();

        System.out.println("Product of 2 and 3: " + calc.multiply(2, 3));
        System.out.println("Product of 2.5 and 3.5: " + calc.multiply(2.5, 3.5));
        System.out.println("Product of 2, 3, and 4: " + calc.multiply(2, 3, 4));
    }
}

Explanation: In the Calculator class, the multiply method is overloaded three times: to multiply two integers, to multiply two doubles, and to multiply three integers. Depending on the arguments, the corresponding method is executed.

  1. String Concatenation with Overloaded Methods:
class StringConcatenator {
    public String concatenate(String a, String b) {
        return a + b;
    }

    public String concatenate(String a, String b, String c) {
        return a + b + c;
    }

    public String concatenate(String a, int b) {
        return a + b;
    }
}

public class TestStringConcatenator {
    public static void main(String[] args) {
        StringConcatenator sc = new StringConcatenator();

        System.out.println(sc.concatenate("Hello, ", "World!"));
        System.out.println(sc.concatenate("Java", " is", " awesome!"));
        System.out.println(sc.concatenate("Number: ", 42));
    }
}

Explanation:

In the StringConcatenator class, the concatenate method is overloaded to handle different types and numbers of parameters: two strings, three strings, and a string with an integer. Each call to concatenate uses the method that matches the provided arguments.

  1. Area Calculation with Overloaded Methods:
class AreaCalculator {
    public double area(double radius) {
        return Math.PI * radius * radius;
    }

    public double area(double length, double width) {
        return length * width;
    }

    public double area(double base, double height, boolean isTriangle) {
        if (isTriangle) {
            return 0.5 * base * height;
        }
        return 0;
    }
}

public class TestAreaCalculator {
    public static void main(String[] args) {
        AreaCalculator ac = new AreaCalculator();

        System.out.println("Area of circle with radius 2.5: " + ac.area(2.5));
        System.out.println("Area of rectangle with length 4 and width 5: " + ac.area(4, 5));
        System.out.println("Area of triangle with base 3 and height 4: " + ac.area(3, 4, true));
    }
}

Explanation:

In the AreaCalculator class, the area method is overloaded to calculate the area of a circle, a rectangle, and a triangle. Each method is called based on the type and number of arguments passed.

Method Overriding in Java

Definition: Method overriding occurs when a subclass provides a specific implementation for a method that is already defined in its superclass. Overriding is determined at runtime and is a form of runtime polymorphism.

Rules for Method Overriding:

  1. The method must have the same name as in the parent class.
  2. The method must have the same parameter list as in the parent class.
  3. The return type must be the same or a subtype of the return type declared in the original overridden method in the parent class.
  4. The method must have the same or a more accessible access modifier.
  5. The method in the child class should not throw a broader checked exception than the method in the parent class.

Example :

class Animal {
    public void sound() {
        System.out.println("Animal makes a sound");
    }
}

class Dog extends Animal {
    @Override
    public void sound() {
        System.out.println("Dog barks");
    }
}

public class TestOverriding {
    public static void main(String[] args) {
        Animal myDog = new Dog();
        myDog.sound();  // Output: Dog barks
    }
}

Explanation:

In the Animal class, there is a sound method that prints a generic message. The Dog class extends Animal and overrides the sound method to print a specific message. When a Dog object is treated as an Animal, the overridden sound method in the Dog class is called at runtime.

Programming Examples for Method Overriding:

  1. Vehicle Class with Overridden Methods:
class Vehicle {
    public void start() {
        System.out.println("Vehicle is starting");
    }
}

class Car extends Vehicle {
    @Override
    public void start() {
        System.out.println("Car is starting");
    }
}

public class TestVehicle {
    public static void main(String[] args) {
        Vehicle myCar = new Car();
        myCar.start();  // Output: Car is starting
    }
}

Explanation:

The Vehicle class has a start method that is overridden in the Car class. When a Car object is treated as a Vehicle, the start method from the Car class is called.

  1. Shape Class with Overridden Methods:
class Shape {
    public void draw() {
        System.out.println("Drawing a shape");
    }
}

class Circle extends Shape {
    @Override
    public void draw() {
        System.out.println("Drawing a circle");
    }
}

public class TestShape {
    public static void main(String[] args) {
        Shape myCircle = new Circle();
        myCircle.draw();  // Output: Drawing a circle
    }
}

Explanation: The Shape class has a draw method that is overridden in the Circle class. When a Circle object is treated as a Shape, the draw method from the Circle class is called.

  1. Employee Class with Overridden Methods:
class Employee {
    public void work() {
        System.out.println("Employee is working");
    }
}

class Manager extends Employee {
    @Override
    public void work() {
        System.out.println("Manager is managing");
    }
}

public class TestEmployee {
    public static void main(String[] args) {
        Employee myManager = new Manager();
        myManager.work();  // Output: Manager is managing
    }
}

Explanation: The Employee class has a work method that is overridden in the Manager class. When a Manager object is treated as an Employee, the work method from the Manager class is called.

Most Popular

Social Media

Categories

On Key

Related Posts

SQL Quries

A Comprehensive Guide to MySQL Queries

MySQL is a widely-used relational database management system that allows for the creation, modification, and management of databases using SQL (Structured Query Language). In this guide, we’ll cover the essential MySQL queries with examples and tables to help you master the basics. Creating a Database Before you can create tables, you need a database. Use

Java All key Concets

Mastering Java: Key Concepts and Examples for Beginners

Welcome to Pivoteduunit’s comprehensive guide to Java programming! This post is designed to help you understand the essential concepts and provide you with practical examples to kickstart your coding journey. Whether you’re new to Java or looking to solidify your basics, we’ve got you covered. Variables Explanation: Variables are containers for storing data values. Data

Overloading and Overriding

Java- Method Overloading and Overriding

Method Overloading Method overloading in Java allows a class to have more than one method with the same name, as long as their parameter lists are different. Overloading is determined at compile-time and is a form of compile-time polymorphism. Rules for Method Overloading: Explanation: In the MathOperations class, there are three overloaded add methods. The

Java Inheritance Programs

Java Inheritance: Exercises, Practice, Solution

In Java, classes can be derived from other classes, allowing them to inherit fields and methods from the parent classes. Definitions: Except for Object, which has no superclass, every class has exactly one direct superclass (single inheritance). If no other explicit superclass is declared, every class implicitly extends Object. Classes can be derived from other