Skip to content
NA

Nizam Alesevic

1 article

November 11, 2020

JAVA Generics

Software Development

JAVA Generics

Concept of generics Java generics allows the creation of a class or a method that can be reused by different data types or objects. This reduces the need for the same implementation throughout the code. Another advantage is that the error checks are performed during the compile time, removing the possibility of runtime errors. The class or a method denoted by <T> is recognized as a generic, where T is a type of parameter. In order to differentiate types of parameters from ordinary classes, single, uppercase letters are used. Unbounded type parameters Let’s create a simple generic class which prints out the value that was previously set: public class Demo<T> { private T value; public void setValue(T value) { this.value = value; } public void printValue() { System.out.println(value); } } We can instantiate this class with the following: Demo<String> onlyString = new Demo<>; Demo<Integer> onlyInteger = new Demo<>; and set the values: onlyString.setValue(“Hello”); onlyInteger.setValue(1); If we try to do something like this, we will get a compilation error: onlyString.setValue(1); Now we can print out the values for both data types, by calling the same method from our generic class: onlyString.printValue(); // “Hello” onlyInteger.printValue(); // 1 Bounded parameter types What if we want to limit classes that can be instantiated from our generic class? This can be achieved with a super keyword for lower, and extends for upper bounds. Imagine having a hierarchy of classes: public class Animal { } public class Bird extends Animal { } public class Eagle extends Bird { } To create a generic class with bounded parameters we can do one of the following: <T extends Animal>- any class that is extended from the Animal, i.e Bird and Eagle <T super Bird>- superclasses of the Bird, i.e Animal, Object "JAVA Generics" Tech Bite was brought to you by Nizam Alešević, Junior Software Engineer at Atlantbh. (more…)

Ready to Achieve More?

We’ll help you reach your goals quickly with an easy and straightforward process to kick off our collaboration. Here’s what happens next.

STEP 1

Discovery Call

Let’s chat to understand your company, project needs, and answer any questions along the way.

STEP 2

Free Consultation

Work closely with our experts to explore the right solutions for your business.

STEP 3

Collaboration Proposal

We'll recommend the best strategy for your goals, ensuring you get the most from our expertise.

STEP 4

30-Day Cancellation
Policy Contract

Spoiler: It’s Never Been Used

Enjoy peace of mind while we deliver excellence from day one—our track record speaks for itself.

Services you're interested in (Optional)