I read the document on Java Generics, and it said that the java 'extends' keyword in connection with Generics means and class which implements that interface.
Based on this, i tried to create generic classes to understand this further. Here is my sample code.
Interface code:
package com.vipin.generics.doubtclear;
public interface DemoInterface1<T> {
void display(T t);
}
Now, I created few simple classes which implements this interface:
package com.vipin.generics.doubtclear;
class myClass<T> implements DemoInterface1<T> {
public myClass(T t) {
}
@Override
public void display(T t) {
System.out.println("Inside display method of myClass, object is ---> "+t);
}
}
class myClass1<T> implements DemoInterface1<T> {
public myClass1(T t) {
}
@Override
public void display(T t) {
System.out.println("Inside display method of myClass1, object is ---> "+t);
}
}
Here is the class which has main, which tries to create objects:
public class DoubtClear1 {
static <T extends DemoInterface1<T>> void myFunc(T t) {
t.display(t);
}
public static void main(String[] args) {
myClass<Integer> iObj = new myClass<Integer>(1);
myClass1<Integer> iObj1 = new myClass1<Integer>(1);
DoubtClear1.myFunc(iObj);
}
}
In main I am creating
myClass<Integer>andmyClass1<Integer>objects.As per my understanding of 'extends' keyword when applied to Generics
myFunc()is capable of taking any object reference which implementsDemoInterface1interface .This is what i am doing in call ==>
DoubtClear1.myFunc(iObj);
However, this is giving me compile-time error:
The method myFunc(T) in the type DoubtClear1 is not applicable for the arguments (myClass<Integer>)
This is really confusing. I am doing what is written in the documentation on this topic and it is failing. I am not sure if my understanding of this topic is correct.
From what I feel, Generics is confusing, and it takes repeated study to really get what this is.
Any information to clear this point really appreciated.
static <Integer extends DemoInterface1<Integer> > void myFunc(Integer t) {which is not true, asIntegeris not aDemoInterface1.From what I feel, Generics is confusing, and it takes repeated study to really get what this is.Yes, it can be confusing at first but it all makes sense, you just need to work out the logic. Stick with it and you'll master it.