Method Overloading with Overloaded Methods That Use Different Parameter Types, Including Custom Objects and Their Properties in Java


Write a Java program to demonstrate method overloading with overloaded methods that use different parameter types, including custom objects and their properties

  • The Student class defines a simple class representing a student with a name and age.
  • The MethodOverloadingDemo class contains two overloaded printStudentInfo methods.
  • The first method takes a Student object as an argument and prints the student's name and age.
  • The second method takes a String representing the student's name and prints only the name.
  • In the main method of OverloadingWithCustomObjectsDemo, an instance of Student named student is created with the name "Leo" and age 25.
  • Both printStudentInfo methods are called, one with the Student object student and the other with a String "Bob".
  • Method overloading allows the same method name to be used for different implementations based on the types of parameters passed.
  • In this case, the appropriate printStudentInfo method is invoked based on the type of the argument passed, either a Student object or a String.

Source Code

public class OverloadingWithCustomObjectsDemo
{
	public static void main(String[] args)
	{
		MethodOverloadingDemo printer = new MethodOverloadingDemo();
 
		Student student = new Student("Leo", 25);
 
		printer.printStudentInfo(student);
		printer.printStudentInfo("Bob");
	}
}
class Student
{
	private String name;
	private int age;
 
	public Student(String name, int age)
	{
		this.name = name;
		this.age = age;
	}
 
	public String getName() // Getters for name and age
	{
		return name;
	}
 
	public int getAge()
	{
		return age;
	}
}
 
class MethodOverloadingDemo
{    
	void printStudentInfo(Student student) // Method to print student's name and age
	{
		System.out.println("Student Info :");
		System.out.println("Name : " + student.getName());
		System.out.println("Age : " + student.getAge());
	}
 
	void printStudentInfo(String name) // Method to print student's name only
	{
		System.out.println("Student Name : " + name);
	}
}

Output

Student Info :
Name : Leo
Age : 25
Student Name : Bob

Example Programs