"Author: Mengxiang Month Blog: Http://blog.csdn.net/mengxiangyue"
In writing a program, we want a function to receive parameters, there is a range of limitations, this time we can consider the use of generic upper and lower bounds to solve. Let's look at a piece of code first and then explain it in detail.
Class point<t>
{
private T x;
Private T y;
Public T GetX ()
{return
x;
}
public void SetX (T x)
{
this.x = x;
}
Public T GetY ()
{return
y;
}
public void Sety (T y)
{
this.y = y;
}
}
public class Demo2
{
// static void Show (POINT<? extends number> P)//This function can only receive number and its subclasses at this point show ( P2) error
static void Show (POINT< super string> P)//This function can only receive String and its parent class at this time show (p1) will error
{
System.out.println (P.getx ());
System.out.println (P.gety ());
}
public static void Main (string[] args)
{
point<integer> p1 = new point<integer> ();
P1.setx (2);
P1.sety (4);
point<string> P2 = new point<string> ();
P2.setx ("43 degrees east longitude");
P2.sety ("34 degrees north latitude");
Show (p1);
Show (p2);
}
In this program we define a function show, which we use after the argument. .....> Here is the question mark, the wildcard character that represents the type of actual argument received. We can see that in the program I first commented on the Entends line of code. This represents the upper limit of the parameter, the received parameter must be number or its subclass, and if this is used, when we call the Show method, the pass P2 will complain, because P2 is not number or its subclasses. Similarly, we use the Super keyword, which represents the upper bound of the parameter, which indicates that the received parameter can only be string or its parent class, when the show method parameter is P1 and does not meet the requirements of the lower limit.
For the upper and lower limits basic use is this, hope to help you.
If there is a mistake, please point out.