Generics with java Coding  


see the example below 
                                                                                                                                                 
   

    There are three classes called A, B and Test. You can see that the main method is called in the test class. You can see a method in class A and the data type of its argument can be viewed as a string. The data type in the B class argument can be viewed as int
    The objects related to that class have been made in the main method and called. A string value has been passed to A class via obj1. An integer value has been passed to B class via obj2.
    Both A and B classes are identical in every respect, and there is only a difference between the data types of the arguments in the two methods





To avoid that difference, we can use the object class at the top of the Java class hierarchy. In that case, we can enter the object data type as the data type of the argument and pass the object of the A class in the main method and then grab the value passed by the A class.

However, there may be some problems there. In the example below, we can see a similar problem. In the main method, if you pass a staring value from an obj1 object, you can get that value from the object type of A class and try to convert that string value into a double value, but that is impossible. But that error is not shown as a compile error, it is shown as a runtime error. It's a disadvantage





We can use Generics to avoid this disadvantage. To avoid the type error, we can create a data type (T) and pass the data and make calls. You can avoid runtime errors that affect the performance of the runtime. The following example shows how to use generics






Comments

Popular posts from this blog

Java Design Patterns

Application Programming Interface (API)