Generics in Java





Java Generics :

Java Generic methods and generic classes enable programmers to specify, with a single method declaration, a set of related methods, or with a single class declaration, a set of related types, respectively. Generics also provide compile-time type safety that allows programmers to catch invalid types at compile time.:

Key Points :

  • In Java, an Interface ,a class and a method can be declared as taking one or more type parameters. If this is the case, the respective class ,method or the interface is said to be generic.
  • Type Parameters are written in angle brackets < > also called diamond symbol. It serves a place holder for type arguments.
  • Each type parameter is replaced by a type argument when we create an object of the generic type.

Generic Method :

Consider the following snippet of code, the following print method can accept the Integer array and display the array elements.
public static void print(Integer[] ob)
{
  for(Integer x: ob){
   System.out.println(x);
  }
 }
So, suppose if we want to perform the similar functionality for other types then Generic Method allows us to write generic form of the above method to work with all types without re-writing the same functionality for each type.
All generic method declarations have a type parameter section delimited by angle brackets (< and >) that precedes the method's return type.
Example:
class Test
{
 public static < E > void print(E[] ob)
 {
  for(E x: ob){
      System.out.println(x);
  }
 }   
 public static void main(String[] args)
 {
   Integer[] x = {1,2,3};
   String[] w = {"Hello","Prowess"};
   print(x);
   print(w);
 }
}
OUTPUT:
1
2
3
Hello
Prowess

Generic Class :

A generic class declaration looks like a non-generic class declaration, except that the class name is followed by a type parameter section.
As with generic methods, the type parameter section of a generic class can have one or more type parameters separated by commas.
Example:
class Demo< E >
{
 E [] ar;
 void print(){
  for(E x : ar){
   System.out.println(x);
  }
 }
}
class Test
{
 public static void main(String[] args)
 {
   Demo< Integer> ob1;
   Demo< Float> ob2;
   ob1 = new Demo< Integer>();
   ob2 = new Demo< Float>();
   ob1.ar = new Integer[2];
   ob1.ar[0] = 1;
   ob1.ar[1] = 2;
   ob2.ar = new Float[2];
   ob2.ar[0] = 5.2f;
   ob2.ar[1] = 7.2f;
   ob1.print();
   ob2.print();
 }
}
OUTPUT:
1
2
5.2
7.2

Generic Interface :

Similar to generic class, we can create Generic Interfaces to implement general prototyping model. The type replacement for the type parameter < > is done at the time of implementation.
Example:
interface Calc< E>
{
 E opr(E a, E b);
}

class Add implements Calc< Integer>
{
 @Override
 public Integer opr(Integer a,Integer b)
 {
  return a+b;
 }
}
class Test
{
 public static void main(String[] args)
 {
  Add ob = new Add();
  Integer sum = ob.opr(20,40);
  System.out.println(sum);
 }
}
OUTPUT:
60

Subtyping Principles :

As we know one type is a subtype of another if they are related by an extends or implements clause.
  • Integer is a subtype of Number
  • ArrayList<E> is a subtype of List<E>
  • List<E> is a subtype of Collection<E>
Subtyping is transitive, meaning that if one type is a subtype of a second, and the second is a subtype of a third, then the first is a subtype of the third.

Substitution Principles :

A list of Number can contain Integer and Double objects (two subtypes of Number).
List<Number> ob;
ob = new ArrayList<Number>();
ob.add(2016); 
ob.add(3.14);
Here, as you can see, the Substitution Principle is applied for the reference type (List) and object type (ArrayList).
The add() method can accept any type which is subtype of Number, thus an Integer and a Double objects can be added to the collection.
The Substitution Principle does not work with the parameterized types, meaning that it is illegal to write:
List<Number> ob;
ob = new ArrayList<Integer>();
 //compile-time error

Bounded Type Parameter :

There may be times when you'll want to restrict the kinds of types that are allowed to be passed to a type parameter. For example, a method that operates on numbers might only want to accept instances of Number or its subclasses.

Bounded Type: We use extends keyword for applying upper bound on type parameter, bounded type is applicable for generic method and class
Syntax : <E extends BoundClass>
Example:
class Test
{
 <E extends Number> void print(E[] ob)
 {
  for(E x: ob){
      System.out.println(x);
  }
 }
}
The above method will work only for array of Number and its sub-types.

Wild Card :

In generic code, the question mark (?), called the wildcard, represents an unknown type.
The wildcard is never used as a type argument for a generic method invocation, a generic class instance creation, or a supertype.

Upper Bounded Wildcard: We use extends keyword for upper bound.
Syntax : <? extends BoundClass>
Example:
class Demo<E>
{
 E x;
 void display(){
  System.out.println(x);
 }
}
class Test
{
 void print(Demo<? extends Number> ob)
 {
  ob.display();
 }
}
The above print method will work only for Demo object of Number and its sub-types.

Lower Bounded Wildcard: We use super keyword for upper bound.
Syntax : <? extends BoundClass>
Example:
class Demo<E>
{
 E x;
 void display(){
  System.out.println(x);
 }
}
class Test
{
 void print(Demo<? super Number> ob)
 {
  ob.display();
 }
}
The above print method will work only for Demo object of Number and its super-types.

Next topic is collections framework




 








Training For College Campus

We offers college campus training for all streams like CS, IT, ECE, Mechanical, Civil etc. on different technologies like
C, C++, Data Structure, Core Java, Advance Java, Struts Framework, Hibernate, Python, Android, Big-Data, Ebedded & Robotics etc.

Please mail your requirement at info@prowessapps.in


Projects For Students

Students can contact us for their projects on different technologies Core Java, Advance Java, Android etc.

Students can mail requirement at info@prowessapps.in



CONTACT DETAILS

info@prowessapps.in
(8AM to 10PM):

+91-9026070669 , +91-9451396824

© 2016, prowessapps.in, All rights reserved