Write a program on Generic Constructor.

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 GenericConstructorDemo contains a generic constructor with a type parameter T that extends Number. This means the constructor can accept any type that is a subclass of Number (e.g., Integer, Float, Double, etc.).
    • Inside the constructor, the argument arg is converted to a double using the doubleValue() method. This ensures that the class can handle different numeric types and store them as a double.

    Creating Objects:

      • In the main method, three objects of GenericConstructorDemo are created, each using a different numeric type (Integer, Float, and Double). The constructor automatically handles the conversion to double.

      Output:

        • The program prints the values passed to the constructor and the converted double values 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.

        Leave a Reply

        Your email address will not be published. Required fields are marked *