Hello,
I was messing around testing out my understanding of Generics when I came across a problem that I believe to be simple, yet I cannot recall the solution to it. At first, I had the value hold an Integer type value of 9. Then I instantiated the value to 9.0, changing its value type to Double. Now I'm trying to change the value of it again, keeping it the same type, but getting it from 9.0 to 12.3. I know that probably adding a constructor would do the job, but I wonder if there's a way to change the value without having to include a constructor in the 'Container' class.
What I've tried:
So I know adding a constructor makes the change work. Also, not adding a constructor but making the 'N value' a field, then using the Setter/Getter would work. Just wondering if there's another way/explanation behind why this is occurring.
My question:
What is/isn't happening that the value of 'value' isn't changing from 9.0 to 12.3 as when I print out it towards the end, it is still 9.0 compared to the 9 to 9.0 change?
Edit: Fixed, was a simple logic error.
Here is my code below:
class Container<N extends Number>{ N value; public N getValue() { return value; } public void setValue(N value) { this.value = value; } //Simple to show of what type our value holds public void showType() { System.out.println(value.getClass().getName()); } } public class PracticeGenerics { public static void main(String[] args) { //We create our 'Container' object not using Generics Container obj = new Container(); //Since our class doesn't have a constructor, we instantiate the value of 'value' to 9 here obj.value = 9; //We display the 'value' type here obj.showType(); System.out.println(obj.value); obj.value = 9.0; obj.showType();//This displays 'java.lang.Double' now instead of 'java.lang.Integer' System.out.println(obj.value);//Prints out the value of 'value' which we changed from an int type '9' to a double type '9.0' //Separate the two different tests System.out.println("---------------------------------------------"); //Creating our 'Container' object using Generics Container<Double> obj2 = new Container<Double>(); obj2.value = 12.3; obj2.showType(); System.out.println(obj2.value); }//end Main }//end Class