0% found this document useful (0 votes)
22 views3 pages

SBL Exp6 TanuSingh

Uploaded by

Prince Kaswala
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views3 pages

SBL Exp6 TanuSingh

Uploaded by

Prince Kaswala
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Experiment 6

Program on method and constructor overloading.

AIM: a) To perform method overloading.

Code:
public 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 double values
public double add(double a, double b) {
return a + b;
}
public static void main(String[] args) {
MathOperations mathOps = new MathOperations();
System.out.println("Sum of 2 and 3: " + mathOps.add(2, 3));
System.out.println("Sum of 1, 2, and 3: " + mathOps.add(1,
2, 3));
System.out.println("Sum of 2.5 and 3.5: " + mathOps.add(2.5,
3.5));
}
}

OUTPUT:
> javac MathOperations.java
> java MathOperations
Sum of 2 and 3: 5
Sum of 1, 2, and 3: 6
Sum of 2.5 and 3.5: 6.0

AIM: b) To perform constructor overloading.

Code:
public class Rectangle {
// TODO: declare length and breadth
private double length;
private double width;

// Constructor with no arguments (default values)


public Rectangle() {
this.length = 1.0;
this.width = 1.0;
}

// Constructor with two arguments (length and width)


public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}

// Constructor with one argument (square)


public Rectangle(double side) {
this.length = side;
this.width = side;
}
public double calculateArea() {
return length * width;
}

public double calculatePerimeter() {


return 2 * (length + width);
}

public static void main(String[] args) {


Rectangle rect1 = new Rectangle(); // Default constructor
Rectangle rect2 = new Rectangle(5.0, 3.0);
Rectangle rect3 = new Rectangle(4.0);

System.out.println("Rectangle 1: Area = " +


rect1.calculateArea() + ", Perimeter = " +
rect1.calculatePerimeter());
System.out.println("Rectangle 2: Area = " +
rect2.calculateArea() + ", Perimeter = " +
rect2.calculatePerimeter());
System.out.println("Rectangle 3: Area = " +
rect3.calculateArea() + ", Perimeter = " +
rect3.calculatePerimeter());
}
}

Output:
> javac Rectangle.java
> java Rectangle
Rectangle 1: Area = 1.0, Perimeter = 4.0
Rectangle 2: Area = 15.0, Perimeter = 16.0
Rectangle 3: Area = 16.0, Perimeter = 16.0

You might also like