Posted by on 31st January 2019

Generic class

A class that can refer to any type is known as generic class. Here, we are using T type parameter to create the generic class of specific type.

class MyGen<T> {
        T obj;

        void add(T obj) {
            this.obj = obj;
        }

        T get() {
            return obj;
        }
    }

Type Parameters

The type parameters naming conventions are important to learn generics thoroughly. The commonly type parameters are as follows:

  1. T – Type
  2. E – Element
  3. K – Key
  4. N – Number
  5. V – Value

Generic Method

Like generic class, we can create generic method that can accept any type of argument.

Let’s see a simple example of java generic method to print array elements. We are using here E to denote the element.

public class TestGenerics4{  
  
   public static < E > void printArray(E[] elements) {  
        for ( E element : elements){          
            System.out.println(element );  
         }  
         System.out.println();  
    }  
    public static void main( String args[] ) {  
        Integer[] intArray = { 10, 20, 30, 40, 50 };  
        Character[] charArray = { 'J', 'A', 'V', 'A', 'T','P','O','I','N','T' };  
  
        System.out.println( "Printing Integer Array" );  
        printArray( intArray  );   
  
       System.out.println( "Printing Character Array" );  
        printArray( charArray );   
    }   
}

Wildcard in Java Generics

The ? (question mark) symbol represents wildcard element. It means any type. If we write <? extends Number>, it means any child class of Number e.g. Integer, Float, double etc. Now we can call the method of Number class through any child class object.

Let’s understand it by the example given below:

    abstract class Shape {
        abstract void draw();
    }

    class Rectangle extends Shape {
        void draw() {
            System.out.println("drawing rectangle");
        }
    }

    class Circle extends Shape {
        void draw() {
            System.out.println("drawing circle");
        }
    }


    class GenericTest {
        //creating a method that accepts only child class of Shape  
        public static void drawShapes(List<? extends Shape> lists) {
            for (Shape s : lists) {
                s.draw();//calling method of Shape class by child class instance  
            }
        }

        public static void main(String args[]) {
            List<Rectangle> list1 = new ArrayList<Rectangle>();
            list1.add(new Rectangle());

            List<Circle> list2 = new ArrayList<Circle>();
            list2.add(new Circle());
            list2.add(new Circle());

            drawShapes(list1);
            drawShapes(list2);
        }
    }

Example 1

    public interface Callback<T> {
        void onSuccess(List<T> response);

        void onError(String error);
    }

    public GenericTypeExample() {
        backgroundJob(new Callback<String>() {
            @Override
            public void onSuccess(List<String> response) {
                Log.e("onSuccess", "List size" + response.size());
            }

            @Override
            public void onError(String error) {
                Log.e("onError", error);
            }
        });
    }

    private void backgroundJob(Callback<String> callback) {
        List<String> list = getList();
        if (list != null) {
            callback.onSuccess(list);
        } else {
            callback.onError("Empty List");
        }
    }

    private <T> List<T> getList() {
        return new ArrayList<>();
    }

Example 2

    public interface Service<T> {
        T execute();
    }

    public class FooService implements Service<String> {

        private final String input1;
        private final int input2;

        public FooService(String input1, int input2) {
            this.input1 = input1;
            this.input2 = input2;
        }

        @Override
        public String execute() {
            return String.format("'%s%d'", input1, input2);
        }
    }
Please follow and like us:

Comments

Be the first to comment.

Leave a Reply


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*


Enjoy this blog? Please spread the word :)