java generics

Java Generics : Method And Constructor

What is Java Generics?

Java Generics are very useful in java program language, using generics we can customize our code and reduce size of program.

 

We can use same constructor and method for different types of wrapper class and data types. For better understand we will see video and example on java generics.

In this program, we will see how to method and constructor work with generics.

 

Programs

class A<T> // Set Class Generics

{

                T value;

                void setValue(T value)

                {

                                this.value = value;

                }

                T getValue()

                {

                                return this.value;

                }

}

class B<T>

{

                T value;

                B(T value)// Generics with Constructor

                {

                                this.value = value;

                }

                T getValue()

                {

                                return this.value;

                }

}

class gen1

{

                public static void main(String args[])

                {

                                A<Integer> obj1 = new A<Integer>();// Integer Generics

                                A<Double> obj2 = new A<Double>();// Double Generics

 

                                obj1.setValue(45);          // Same method set Integer value

                                obj2.setValue(45.67);    // same method set Double Value

                                System.out.println(“Integer Value : ” + obj1.getValue());

                                System.out.println(“Double Value : ” + obj2.getValue());

 

                                // Call to Constructor Generics

                                B<String> b1 = new B<String>(“Hello Generics”);

                                B<Double> b2 = new B<Double>(45.78);

 

                                System.out.println(“Constructor Generics”);

                                System.out.println(“String Value : ” + b1.getValue());

                                System.out.println(“Double Value : ” + b2.getValue());

                }

}

Output:

Integer Value : 45

Double Value: 45.67

String Value: Hello Generics

Double Value: 45.78

 

Video available on YouTube.

 


If you have any query on blog example, you can directly comment us or subscribe our website

Earn Money Online

Share and Enjoy

  • Facebook
  • Twitter
  • Delicious
  • LinkedIn
  • StumbleUpon
  • Add to favorites
  • Email
  • RSS

377total visits,5visits today


mayank

Hello, I am Maddy a Java blogger, trainer and developer

Related articles

Leave a Reply

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

Your comments (*)

Name (*)

Your full name please.

Email address (*)

Used for gravatar.

Website

Link back if you want.

Enter Captcha Here :*

Reload Image

EmailEmail
PrintPrint