Method Overloading with Different Access Modifiers in Java


Create a Java program to demonstrate method overloading with different access modifiers

The Java class Shapes showcases method overloading and access modifiers. It defines multiple draw methods, each with different parameter lists and access modifiers. The first draw method has no parameters and prints "Drawing shape". The second draw method takes a String parameter shapeName and prints "Drawing" followed by the provided shape name. The third draw method takes an integer parameter sides and prints "Drawing a shape with [number of sides] sides". The fourth draw method is marked as private and takes a double parameter area, printing "Drawing a shape with area [provided area]". In the main method, instances of Shapes are created, and various draw method calls are made, showcasing method overloading and demonstrating different behaviors based on the method parameters.

Source Code

class Shapes
{
	void draw()
	{
		System.out.println("Drawing shape");
	}
 
	public void draw(String shapeName)
	{
		System.out.println("Drawing " + shapeName);
	}
 
	protected void draw(int sides)
	{
		System.out.println("Drawing a shape with " + sides + " sides");
	}
 
	private void draw(double area)
	{
		System.out.println("Drawing a shape with area " + area);
	}
 
	public static void main(String[] args)
	{
		Shapes shape = new Shapes();
		shape.draw();
		shape.draw("Circle");
		shape.draw(4);
		shape.draw(25.0);
	}
}

Output

Drawing shape
Drawing Circle
Drawing a shape with 4 sides
Drawing a shape with area 25.0

Example Programs