1:write a program to create a class and implement the concept of constructor overloading ,method overloading, static method ?
class MathUtils {
// Constructor Overloading
MathUtils() {
System.out.println("Default constructor");
}
MathUtils(int num) {
System.out.println("Constructor with int parameter: " + num);
}
MathUtils(double num) {
System.out.println("Constructor with double parameter: " + num);
}
// Method Overloading
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
String add(String str1, String str2) {
return str1 + str2;
}
// Static Method
static void printMessage(String message) {
System.out.println("Static method message: " + message);
}
}
public class Main {
public static void main(String[] args) {
// Constructor Overloading
MathUtils defaultMath = new MathUtils();
MathUtils intMath = new MathUtils(5);
MathUtils doubleMath = new MathUtils(3.14);
// Method Overloading
MathUtils mathUtils = new MathUtils();
int sum1 = mathUtils.add(2, 3);
double sum2 = mathUtils.add(2.5, 3.5);
String concatenated = mathUtils.add("Hello, ", "world!");
System.out.println("Sum of integers: " + sum1);
System.out.println("Sum of doubles: " + sum2);
System.out.println("Concatenated strings: " + concatenated);
// Static Method
MathUtils.printMessage("This is a static method example.");
}
}
No comments