Definitions of Java generic classes

Source: Internet
Author: User

The definition of generics, compared to the normal class definition, first adds a type variable identified by the angle brackets after the class name, typically denoted by T. T can be used anywhere in a generic type. This is also true for generalization interfaces.

Let's take a look at the generic type of box and box's code:

(1) Definition of ordinary box


public class mybox{
Private Object object;
public void Add (Object object) {
This.object = object;
}
public object Get () {
return object;
}
}

(2) Generic definition of box class

public class mybox<t>{
Private T T;
public void Add (T t) {
THIS.T = t;
}
Public T get () {
return t;
}
}

In the generic definition of the Mybox class, the "public class Mybox" in the class declaration is changed to "public class mybox<t>", and all objects in the Mybox class body are replaced with T, which defines mybox as an abstract type that can hold various types of object containers of a certain type .

Package practice;


public class Myboxtest {

public static void Main (string[] args) {
TODO auto-generated Method Stub
mybox<string> Abox = new mybox<string> ();
Abox.add (New String ("GA Suen"));
String i = Abox.get ();
System.out.println (i);
}
}

Output:

ga Suen

public class Myboxtest {

public static void Main (string[] args) {
TODO auto-generated Method Stub
mybox<integer> Abox = new mybox<integer> ();
Abox.add (Newinteger ("2018"));
Integer i = Abox.get ();
System.out.println (i);
}
}

Output:

2018

Definitions of Java generic classes

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.