generic concept in Java – Programmerbay https://programmerbay.com A Tech Bay for Tech Savvy Sun, 21 Mar 2021 17:22:38 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.5 https://programmerbay.com/wp-content/uploads/2019/09/cropped-without-transparent-32x32.jpg generic concept in Java – Programmerbay https://programmerbay.com 32 32 Bounded Type Parameter in Java Generics https://programmerbay.com/bounded-type-parameter-in-java-generics/ https://programmerbay.com/bounded-type-parameter-in-java-generics/#respond Sun, 21 Mar 2021 15:03:32 +0000 https://programmerbay.com/?p=8314 In Java Generics, a situation can arise where we need to restrict or bound an object type to specific types only in order to narrow down the acceptable types supported in the type parameter. For instance, a method that deals with numbers, should accept Number and its sub-classes.

Screenshot from 2021 03 09 17 53 26

Bounded Types:

The concept of limiting type parameter upto certain type is known as bounded types. In this, extends keyword is used to bound the type parameter.

It simply tells the compiler to allow only parent class or its subclasses types that T has extended, meaning,it restricts in passing types.

For example, if T extends Number, then only the type of Number class itself or its child classes such as integer,double and others are applicable.

Point to remember:

– In generics, one can extends an interface too.

– Super keyword terminology is not applied with Type Parameter

– extends keywords is used for bounded types

Syntax :

class A <T extends AnyClassName or InterfaceName> {​ // it can be class or interface

​
}​

Java program to demonstrate Bounded Type Parameter

public class BoundedTypeExample<T extends Number> {

void print(T num){
System.out.println("Only Number is allowed "+ num);
}

public static void main(String[] args) {
BoundedTypeExample<Integer> boundedTypeExample = new BoundedTypeExample();
boundedTypeExample.print(4);

}
}

However, passing string type would trigger compile time error.

public class BoundedTypeExample<T extends Number> {

void print(T num){
System.out.println("Only Number is allowed "+ num);
}

public static void main(String[] args) {
BoundedTypeExample<String> boundedTypeExample = new BoundedTypeExample(); // Type parameter 'java.lang.String' is not within its bound; should extend 'java.lang.Number'
boundedTypeExample.print("4");

}
}

Is it Possible to extend class and interface together in generics ?

When there is a need of having type that must be type bounded to a class and at the same time, it  should implement an interface. For such situation, there is a way to achieve this functionality.

Syntax:

class ClassName < T extends AnyClassName & AnyInterfaceName >{

}

The syntax simply means, an object of type T must extend the given class and implement the interface at the same time. This is another way to define bounded type.

It is important to remember that when using class and interface in combination, always class comes first and then after interfaces.
However, multiple classes cannot be extended since java doesn’t allow Multiple inheritance concept.

Java Program to demonstrate Bounded Type Parameter with combination of Class and Interface

public class BoundedTypeExample<T extends Number & Serializable> {

void print(T num){
System.out.println(num);
}

public static void main(String[] args) {
BoundedTypeExample<Integer> boundedTypeExample = new BoundedTypeExample<>();
boundedTypeExample.print(2);

}
}

Explanation: Above example, simply prints integer value, and integer is subclass of Number and also Implement Serializable interface.

]]>
https://programmerbay.com/bounded-type-parameter-in-java-generics/feed/ 0
What Is The Purpose Of Generics In Java ? https://programmerbay.com/what-is-the-purpose-of-generics-in-java/ https://programmerbay.com/what-is-the-purpose-of-generics-in-java/#respond Sun, 21 Mar 2021 14:26:23 +0000 https://programmerbay.com/?p=8306 The purpose of generics in Java is to offer type safety and to overcome type casting problem.

Type safety can be defined as the concept of holding a correct data by a variable with respect to its type. It means, if a variable is capable of holding string type then it should not allow other types. It prevents type errors, making the compiler efficient to validate types at compile time. Screenshot from 2021 03 07 18 29 08 1

The Generic concept was mainly introduced to make collection type safe. Since, collection framework deals with objects, as a result, it can hold various object types in form of element which doesn’t guarantees type safety.

Here’re two main purpose Of Generics In Java:

– To provide type safety :

In Java, String, arrays are type safe, meaning, no other data is allowed other than itself. for example.

public class TypeSafeExample {
public static void main(String[] args) {
Integer[] rollNumbers = new Integer[20];
rollNumbers[0] = 1;
rollNumbers[1] = 2;
rollNumbers[3] = "3"; // Would throw Incompatible types. Found

System.out.println("Roll Numbers : ");
for (int i = 0; i < rollNumbers.length; i++) {
System.out.println(rollNumbers[i]);
}

}
}

Error :

Incompatible types. Found: 'java.lang.String', required: 'java.lang.Integer'

In above example, an array of integer can hold only integer values, otherwise, it would give compile time error. This is why, array guarantees the elements that it is carrying, always of same type.

However, when Java haven’t purposed the Generic programming, it wasn’t fully type safe.

– To resolve type casting problems :

Type casting is a concept of converting a value from one type to another compatible data type and assigning it to the respective variable on which the casting is performed. Since, collection can consists elements of various types and at the time of retrieval, type casting problem can be occurred which leads to runtime error. Like, below example.

package generics;

import java.util.ArrayList;
import java.util.List;

public class TypeSafeExample {
public static void main(String[] args) {
List rollNumbers = new ArrayList();
rollNumbers.add(1);
rollNumbers.add(2);
rollNumbers.add("3");
System.out.println("Roll Numbers : "+rollNumbers);

// When try to retrive and store to it string type object
for (int i=0; i<rollNumbers.size();i++){
String rollNumber;
rollNumber = (String) rollNumbers.get(i); // Runtime Error class java.lang.Integer cannot be cast to class java.lang.String
System.out.println(rollNumber);
}
}
}
Runtime Error class java.lang.Integer cannot be cast to class java.lang.String

In order to overcome these problem, Java introduced generics concept.

How to Overcome from the problem of Type Safety in Collection?

To make an arraylist to store only same type of element, we need to create arraylist of Integer. As given below.

public class TypeSafeExample {
    public static void main(String[] args) {
        
       List<Integer> rollNumbers =  new ArrayList<Integer>();
        rollNumbers.add(1);
        rollNumbers.add(2);
        rollNumbers.add("3"); // Compile time errror
        System.out.println("Roll Numbers  : "+rollNumbers);
        
    }
}

It is now type safe, since it guarantees the type of elements expected within an ArrayList. Further, It also takes care of type casting problem as it is no longer required to perform by the compiler which was triggering runtime errors previously.

]]>
https://programmerbay.com/what-is-the-purpose-of-generics-in-java/feed/ 0
What is Generics in Java with Example ? https://programmerbay.com/what-is-generics-in-java-with-example/ https://programmerbay.com/what-is-generics-in-java-with-example/#respond Sun, 21 Mar 2021 13:31:53 +0000 https://programmerbay.com/?p=8191 Generic programming is a way of creating classes, interfaces, and methods to work with various data types. It provides the flexibility to write a feature that is independent of any specific datatype.

In simple words, it allows us to create a class, interface, or method that accepts various datatypes automatically in the parameterized way. Therefore, Generics concept is also termed as parameterized type.

In Java, the Generics concept is one of the crucial features and introduced in JDK 5.

After Generics addition, Java becomes a Type Safety Language. As we know, Object class is the root class of all other classes, and therefore, reference from any type is acceptable which leads to a lack of type safety.

Type Safety ensures prevention from uncertain behavior of a program by verifying a variable holding a value as per its datatype in order to avoid type errors while compilation.

Java Generics is similar to C++’s Standard Template Library (STL) but both languages follow different approaches.

The major impact of Generics concept can be seen in the collection framework particularly.A collection framework offers various classes (such as ArrayList ,LinkedList, HashMap) and interfaces (such as List,Map). It deals with a group of objects and was not type safe before Generics were introduced. After addition of generics, the collection becomes type safe as they start accepting type parameter in form of argument , for example List<Integer> listObj = new ArrayList<>() .

Why we use Generics in Java :

  • It gradually improves code usability
  • It ensures type safety
  • It resolves the type casting problem
  • It enables us to write a generic algorithm that works with datatypes independently

How to Create a Generic Class in Java ?

image 2021 02 14 193256

When a class accepts type parameter within an angular notation, it is considered as a generic type ,in other words, parameterized type.

Syntax:

class Test<T>{

}

T stands for Type Parameter.

Some Important points related to Generics

  • Generic cannot be used with primitive type, it only works with a reference type.
  • Polymorphism doesn’t apply on Type Parameter, i.e ArrayList<Object> obj = new ArrayList<String>(); // would throw compile time error
  • One generic type reference can’t be assigned to another generic type reference.
  • Generic concept is applicable at compile time, but no such concept is there for runtime.
public class GenericClassExample<T> {
    T instanceVariable;

    public T getInstanceVariable() {
        return instanceVariable;
    }

    public void setInstanceVariable(T instanceVariable) {
        this.instanceVariable = instanceVariable;
    }

    public static void main(String[] args) {
        GenericClassExample<String> stringObj = new GenericClassExample<>();
        stringObj.setInstanceVariable("I am String Type !");
        System.out.println("Printing String Type :" + stringObj.getInstanceVariable());

        GenericClassExample<Integer> integerObj = new GenericClassExample<>();
        integerObj.setInstanceVariable(4);
        System.out.println("Printing Integer Type :" + integerObj.getInstanceVariable());
    }
}

Output :

Printing String Type :I am String Type !
Printing Integer Type :4

How to Create Generic Method in Java ?

It is possible to create a generic method with generic and non generic classes.

Syntax :

<Type parameter > returnType methodName(params);
public class GenericMethodExample {

    public <T> void printValues(T value) {
        System.out.println("Value : " + value);
    }

    public static void main(String[] args) {
        GenericMethodExample obj = new GenericMethodExample();
        obj.printValues(43);
        obj.printValues("ProgrammerBay");
        obj.printValues(54.43);
    }
}

Output:

Value : 43
Value : ProgrammerBay
Value : 54.43

Bounded Type Parameter

It allows us to limit the object type that can be passed through type parameter by using extends clause.

Syntax :

<T extends className or interfaceName>

Now, the class and its subclasses, or in case of interface, interface and its implementing classes, can be replaced with Type parameter. For instance, suppose type parameter extends Number class, then only the Number class object itself or those classes that extends it can be substituted with T, such as Integer, Short, Double and more.

Java Program to show the working of Bounded Type Parameter

public class Main <T extends Number>
{
    private void print(T x){
        System.out.println("Number : "+x);
    }
    
  public static void main(String[] args) {
    Main<Integer> integerObj = new Main<>();
    integerObj.print(10);
  }
}

Output :

Number : 10

Passing String Type Parameter would through :

Main<String> StringObj = new Main<>();
  integerObj.print("Num");
 error : type argument String is not within bounds of type-variable T

]]>
https://programmerbay.com/what-is-generics-in-java-with-example/feed/ 0