4.A] Write a program on Generic Constructor.
Answer:
Generic Constructor in Java:
A generic constructor in Java is a constructor that has one or more type parameters. These type parameters are independent of the generic parameters of the class and are specified when the constructor is invoked.
Program Demonstrating a Generic Constructor:
class GenericConstructorDemo {
private double value;
// Generic constructor with a type parameter T
<T extends Number> GenericConstructorDemo(T arg) {
value = arg.doubleValue(); // Convert the argument to double
System.out.println("Constructor called with: " + arg);
}
// Method to get the value
public double getValue() {
return value;
}
public static void main(String[] args) {
// Create objects of GenericConstructorDemo using different types
GenericConstructorDemo obj1 = new GenericConstructorDemo(10); // Integer
GenericConstructorDemo obj2 = new GenericConstructorDemo(10.5f); // Float
GenericConstructorDemo obj3 = new GenericConstructorDemo(99.99); // Double
// Display the values
System.out.println("Value from obj1: " + obj1.getValue());
System.out.println("Value from obj2: " + obj2.getValue());
System.out.println("Value from obj3: " + obj3.getValue());
}
}Explanation:
Generic Constructor:
- The class
GenericConstructorDemocontains a generic constructor with a type parameterTthat extendsNumber. This means the constructor can accept any type that is a subclass ofNumber(e.g.,Integer,Float,Double, etc.). - Inside the constructor, the argument
argis converted to adoubleusing thedoubleValue()method. This ensures that the class can handle different numeric types and store them as adouble.
Creating Objects:
- In the
mainmethod, three objects ofGenericConstructorDemoare created, each using a different numeric type (Integer,Float, andDouble). The constructor automatically handles the conversion todouble.
Output:
- The program prints the values passed to the constructor and the converted
doublevalues stored in the objects.
Output:
Constructor called with: 10 Constructor called with: 10.5 Constructor called with: 99.99 Value from obj1: 10.0 Value from obj2: 10.5 Value from obj3: 99.99
Summary:
This program demonstrates the use of a generic constructor in Java, allowing for the flexibility to initialize objects with various numeric types while converting and storing them as a double. This feature enhances the reusability and type safety of constructors in classes.
