Generics in java that allow to make a classes , methods and interface , that can be operate on any specified type while providing compile time safly , that enable you to write reusable and type-safe code without relying on object and casting , the type parameter is specified within angle-bracket <>
We have a some advantage of using Generics
- Type safely
- Code Reusable
- Readability and Maintainability
See the Example code .
In this Programme we have a Generic class
in the class we have a one variable,
and two method and both method a generic type define
in the class am not define any type in variable even both
method and **method parameter **also
This is our new generic Method outside of class
this method work is take a argument and print but am not define menully in method parameter
*when method is call then am define there type *
This Line Of Code use generic class method
am create a object of my password class one time ,
and am define my object type is String ,
then am call my generic class method setPass() and set password string type,
And my generic method also call and print my password from password object
Same as it is
am create my new object of password an pass int type of my object and set int password and print using my generic method
NOW TALK ABOUT THAT IS IN JAVA GENERIC
so in java generic is a TYPE PERAMETER or PLACEHOLDER
thar represent a type that will be specified within a generic class , method and interface is used,
it is **not a KEYWORD **but a convention to signify a generic type.
UNDERSTAND
role of
- > It allow to create classes , method and interface the can work with a any type in a type manner.
- > At the time of use (during object creation and method calling ) is replaced with actual type like (String , Integer) .
*COMMON CONVERTION TYPE PERAMETERS *
- T -> type (most common use)
- E -> Elements (use in collection)
- K -> (use in maps)
- V -> (use in maps)
- N -> numbers
- S , U , V -> multiple types
Top comments (0)