Generics in Java
Create a generic Class Demo:
class Demo <T>
{
void method(T obj) //method can take any type of data type by default it is object.
{}
}
public static void main (String [] arg)
{
Demo demo = new Demo(); //T is a object.
demo.method("string");
demo.method(10);
}
Demo <String> demo1 = new Demo<String>();
Demo <Integer> demo2 = new Demo<Integer>();
Generics works only with objects, so we cannot use for primitive data types.
Demo <int> obj3 = new Demo<int>(); // Its illegal
One generic type is not compatible with another version of the same generic type.
demo1 = demo2 //will give error because both have different type compatible.
class Demo <T>
{
void method(T obj) //method can take any type of data type by default it is object.
{}
}
public static void main (String [] arg)
{
Demo demo = new Demo(); //T is a object.
demo.method("string");
demo.method(10);
}
Demo <String> demo1 = new Demo<String>();
Demo <Integer> demo2 = new Demo<Integer>();
Generics works only with objects, so we cannot use for primitive data types.
Demo <int> obj3 = new Demo<int>(); // Its illegal
One generic type is not compatible with another version of the same generic type.
demo1 = demo2 //will give error because both have different type compatible.
Comments
Post a Comment