Home > Back-end >  Java pakchoi consult everybody, why does it have to be T class type, the same package class not T cl
Java pakchoi consult everybody, why does it have to be T class type, the same package class not T cl

Time:04-24

Why can't I call in the Domain class TestObject Max method in the class, and toString can? The main function of the new TestObect object call Max method is successful, not passed as a parameter

Domain classes -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --

Public static Void fun5 args (T) {

String STR=args. The toString ();
The args. Max (1, 2);///////////////////no
System.out.println(str);
}





Public static void main (String [] args) {

TestObject TestObject=new TestObject ();

TestObject. Max (1, 2);//////////////////////you can call
Fun5 (testObject);
TestObject class -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --

@ Override
Public String toString () {
Return TestObject {" + "
"The index=" + index +
", STR='" + STR +' \ ' '+
"-- -- -- -- -- -- -- -- -- -- -- -" +
'} ';
}

Public int Max (int a, int b) {
Return a & gt; b? a : b;
}

CodePudding user response:

The
refer to the original poster obitosbb response:
why can't I call in the Domain class TestObject Max method in the class, and toString can? The main function of the new TestObect object call Max method is successful, not passed as a parameter

Domain classes -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --

Public static Void fun5 args (T) {

String STR=args. The toString ();
The args. Max (1, 2);///////////////////no
System.out.println(str);
}





Public static void main (String [] args) {

TestObject TestObject=new TestObject ();

TestObject. Max (1, 2);//////////////////////you can call
Fun5 (testObject);
TestObject class -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --

@ Override
Public String toString () {
Return TestObject {" + "
"The index=" + index +
", STR='" + STR +' \ ' '+
"-- -- -- -- -- -- -- -- -- -- -- -" +
'} ';
}

Public int Max (int a, int b) {
Return a & gt; b? a : b;
}


The tostring method is the object class, the object is the parent class of all classes, so no matter what class you can call, Max method can not, of course, who knows what the args refers to that class,
Is stated in the main TestObject class, can call the method, of course, this is the foundation,

CodePudding user response:

T is a generic type, if you need to use the TestObject method need to convert the args forced to TestObject type to call Max method, if you args parameter passed in is not a TestObject type, the following statement complains
 
(TestObject) args. Max (1, 2);

CodePudding user response:

This is the use of the generic, not generic is explained, the default is Object, want to call can be changed to the following..
Public static Void fun5 args (T) {...

  • Related