Reputation: 99
I have the following code:
public class Inheritance {
class A<T,U,V>{
}
class B<T,U,V> extends A<T,U,T>{
}
}
Could somebody explain me, how it actually works? Does the Class B extend only A class, which parameters are "T,U,T", or it extends the actual A"T,U,V" class?
Upvotes: 2
Views: 922
Reputation: 601
Let put it into real example:
public class Inheritance {
public static class A<T,U,V>{
T t;
U u;
V v;
A(T t, U u, V v) {
this.t = t;
this.u = u;
this.v = v;
}
T getT() {return t;}
U getU() {return u;}
V getV() {return v;}
}
public static class B<T,U,V> extends A<T,U,T>{
public B(T t, U u, V v) {
super(t, u ,t);
}
}
public static void main(String[] args) {
B<Boolean, Integer, String> b = new B<>(false, 1, "string");
// 't' attribute is Boolean
// since type parameter T of class B is Boolean
Boolean t = b.getT();
// 'v' attribute is Boolean
// since type parameters T and V of class A must have the same type as
// type parameter T of class B
Boolean v = b.getV();
}
}
Basically class B extends class A (which has three generic params). By declaring B<T,U,V> extends A<T,U,T>
you just bind the A's first and A's third generic param to the same type of B's first param
As shown in example in constructor of class B we have three distinct types - Boolean, Integer, String, but in constructor of class A we have only two distinct types Boolean, Integer because 1st and 3th constructor param of class A are both bound to Boolean type
More on generics and inheritence can be found here: https://docs.oracle.com/javase/tutorial/java/generics/inheritance.html
Upvotes: 2
Reputation: 405
In this code, the templated type "identifiers" for each class are not linked to each other, let me modify the snippet to explain what I mean :
public class Inheritance {
class A<T,U,V> { }
class B<I,J,K> extends A<I,J,I>{ }
}
The code is the same as before. You can see that there is no "naming" correlation between I,J,K and T,U,V.
Here the types I and J are forwarded to A. From A's perspective, a substitution is made with : T=I, U=J, V=I.
Upvotes: 2
Reputation: 49606
Does the Class B extend only A class, which parameters are "T,U,T"
Yes, exactly.
or it extends the actual A"T,U,V" class?
It's a template, there are no actual generic parameters. It's a way to match your own parameter types with the parent's ones. If there is a B<String, Integer, Long>
instance, there will be a parent object A<String, Integer, String>
backing it.
Upvotes: 3
Reputation: 57114
A
's T
= B
's T
A
's U
= B
's U
A
's V
= B
's T
B<String, Integer, Void> b = null;
A<String, Integer, String> a = b;
Upvotes: 4