Bounded type Parameter – 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.3 https://programmerbay.com/wp-content/uploads/2019/09/cropped-without-transparent-32x32.jpg Bounded type Parameter – 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 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