Verasity Integration with YouTube!

Watching your favourite content is rewarding for you because it’s entertaining. Now imagine being entertained and rewarded with a cryptocurrency that has value. We are proud to announce that we have…

Smartphone

独家优惠奖金 100% 高达 1 BTC + 180 免费旋转




Generics in Java

Hello everyone,

Today I will be going to explain about Generics concept in Java programming language. Guys this is a awesome mechanism for type safety since Java JDK 1.5.

This mechanism only works in compile time. Simply, we can understand this concept using the example in below,

I just create a Hospital class,

The above code we can insert both Doctor and Teacher objects into Hospital class, because the hospital class takes objects in type of Object class. So we can put any object type into the details method.

But in this case there is no type safety. Then what we can do is, we can use a parameter instead of Object reference(like T) in the Hospital class. Then when we are making Hospital object, we should pass the type of object which we want to send. Then that object type can only be added to the Hospital class.

Let’s we modify the above class,

We can modify Hospital class as follows,

So now when we are going to make a Hospital object, we should pass the parameter type that we need.

If we don’t pass any object type to T , then it takes Object type by default.

Here , hospital.details(new Teacher(“T001”, 60000)); line has compile error. Because the object type that have been passed to Hospital object is Doctor (<Doctor>).

Usually Generics are used in Java Collection classes. Also we can used generics in method overloading. I hope you got some idea about the Generics concept in Java. We will discuss about more details in near future.

Thank you!!

Add a comment

Related posts:

The Way We Think About Sustainability is B.S.

Understanding Sustainability is the foundation of everything. Let’s create some context so we can apply the principles of sustainability in our organizations and in our lives. We’ve been throwing…

Annapurna Base Camp Short Trek

The Annapurna Base Camp Short Trek is the ideal trek if you want to experience the mountains in a short time. It is a rushed version of Annapurna Sanctuary Trek–17 days for trekkers with short time…

The Life Dynamic of Run and Return

Chet is the letter of life (chaim, from the root chayah, whose most important letter is chet). We are taught in Chassidut that there are two levels of life “essential life” and “life to enliven.” God…