Generic interfaces and generic methods

Source: Internet
Author: User

Definition of generic interface: the interface defined with generics becomes a generic interface

Interface message<t> { // generic interface

publicString Echo (T msg);

}

In Java, there are two ways to implement a generic interface

1, continue to define generics on subclasses, and this generic type continues to be used on the interface

Interface message<t> { // generic interface

publicString Echo (T msg);

}

class messageimpl<t> Implements message<t> {

publicString Echo (T msg) {

return"ECHO:"+ msg;

}

}

public class testdemo {

     public static void main (string[] args) throws exception {

         message<string>msg = new messageimpl< String> ();

System. out . println (Msg.echo (" Zhang San "));

}

}

2, set the specific type on the subclass

Interface message<t> { // generic interface

publicString Echo (T msg);

}

class Messageimpl Implements message<string> {

publicstring Echo (String msg) {

return"ECHO:"+ msg;

}

}

public class testdemo {

     public static void main (string[] args) throws exception {

         message<string>msg = new messageimpl ();

System. out . println (Msg.echo (" Zhang San "));

}

}

Generic methods:

public class testdemo {

publicstaticvoidmain (string[] args) throwsException {

integerresult[] = get(1, 2, 3);

         for ( int temp:result) { // Even automatic unpacking contains

System. out . println (temp);

}

}

     public static <T> t[] Get (T ... args ) { //T

returnargs;

}

}


This article from "inprovence" blog, declined reprint!

Generic interfaces and generic methods

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.