Generics : Creating custom generic classes

The following two tabs change content below.
Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

Latest posts by Prasad Kharkar (see all)

Hello all, In the previous part of this generics series, we learned about The WildCard Operator. In this part, we are going to see how to create custom generic classes.

But what to create custom generic classes?

Consider a Library. We can have a book library of audio library or cd library, whatever.Library class is.

Now if we want to make a library of books, then we need to extends this class.

We created BookLibrary but there are a lot of issues here.

  • We have to create a new class just to make it a library of books.
  • We have to check the type of Item in returnItem method as the overriding method parameter type must be that of superclass method.
  • What we we need to make libraries of books, cds, news papers, magazines and lots of them. Are we going to create a separate class for that? Of course not.

What we need is a generic way to do this. We need to create a custom generic class.

So we will create a generic library like this.

Let us create Library now

 

 

This outputs,

This means we can successfully create a generic type which can type any Type as argument and we can perform operations on it. We do not have to write Type specific methods. Generics handles everything.

Share Button

10 comments for “Generics : Creating custom generic classes

  1. Animesh
    October 30, 2014 at 5:49 pm

    Good explanation !!

  2. Norrey
    July 1, 2015 at 3:03 pm

    Thanks for the post. It was very helpful.

  3. Maha
    October 22, 2015 at 7:00 pm

    HI Prasad
    Your post on generics custom classes explained the concept in simple way.Thanks a lot.

    • October 26, 2015 at 11:03 am

      Hi Maha, I am glad this was useful. Keep learning.

      • alakhya
        August 17, 2016 at 9:25 pm

        Could you please tell us why java is not allowing to create

        Object Ob=new T(); //Error

        • August 18, 2016 at 4:50 pm

          This is because T is not a defined class. It is simply a placeholder.

  4. Jagadeesh
    May 26, 2016 at 1:54 pm

    Can you show code for Book and CD implementation?

    • May 26, 2016 at 2:45 pm

      Hi Jagadeesh, those are simple Plain Old Java Objects, you can create your own Book and CD classes and try below code, I will help if some problem comes.

      • Jagadeesh
        June 16, 2016 at 6:25 pm

        Yep!! thanks for the help, can we use generics for implementing some common methods that can be implemented other than storing and retrieving objects?

  5. Amit B
    July 18, 2016 at 1:22 pm

    Great explanation!

Leave a Reply

Your email address will not be published. Required fields are marked *