Let's say I got classes A,B,C such that B
extends A
and C
also extends A
.
Now I got 2 different classes, lets call them MyClassB
and MyClassC
with a member of ArrayList<B>
and ArrayList<C>
respectfuly.
Since many actions in MyClassB
and MyClassC
are the same and are only done on the different type of ArrayList, I wanted to create a new abstract class MyClassA
which will have an implementation of the same actions on an ArrayList<A>
for both classe, since A
is the common part which the actions are the same on.
So I tried creating a method in the new MyClassA
class which receives a list as an argument and is supposed to make the action on that list. However, I can't pass an ArrayList<B>
to the method where it expects ArrayList<A>
.
So what can I do in order to keep the same actions in a different class and not repeat the code in 2 different classes?
In a nutshell, generics enable types (classes and interfaces) to be parameters when defining classes, interfaces and methods. Much like the more familiar formal parameters used in method declarations, type parameters provide a way for you to re-use the same code with different inputs.
< T > is a conventional letter that stands for "Type", and it refers to the concept of Generics in Java. You can use any letter, but you'll see that 'T' is widely preferred. WHAT DOES GENERIC MEAN? Generic is a way to parameterize a class, method, or interface.
Implementation of Language Features Basically, that means that the CLR recognizes the difference between, for example, List<int> and List<String>, whereas the JVM can't (Java implemented Generics as part of the compiler).
class MyClassA<T extends A>
{
ArrayList<T> list;
public MyClassA(ArrayList<T> list)
{
this.list = list;
...
class MyClassB extends MyClassA<B>
{
MyClassB(ArrayList<B> list)
{
super(list);
Try with generics:
public class MyClassA<T extends A> {
public void doSomething(ArrayList<T> list) {
// do something
}
}
Now MyClassB
and MyClassC
can inherit from it and you can work with the list normally.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With