Java 16-7 generic method and generic interface (generic class similar)

Source: Internet
Author: User


Write a Objecttool class

Generic method: Defines a generic type on a method
Format public < generic type > return type method name (generic type)
The benefits are:
This generic method can receive any type of data

1  Public class Objecttool {2publicvoid  show (T t) {3System.out.println (t ); 4 }5 }


Write a test class again

 1  public  class   Objecttooldemo { public  static  void   main (string[] args) { 3  objecttool ot =   Objecttool ();  4  ot.show ("Hello" );  5  ot.show (100 6  ot.show (true   7   8  }


Write a generic interface class first
Generic interface: Defines generics on an interface


1  Public Interface Inter<t> {2publicabstractvoid  show (T t); 3 }

Implementation class:

1 /* 2 Implementing a class when implementing an interface3 The first case: you already know what the type is.4 */5 //Public class Interimpl implements inter<string> {6 //7 //@Override8 //Public void Show (String t) {9 //System.out.println (t);Ten //    } One // } A  - //The second case: I don't know what type it is. -  Public classInterimpl<t>ImplementsInter<t> { the  - @Override -  Public voidShow (T t) { - System.out.println (t); + } - } +  A /*    

Test class

1  Public classInterdemo {2  Public Static voidMain (string[] args) {3 //test of the first case4 //inter<string> i = new Interimpl ();5 //i.show ("Hello");6 7 // //test of the second case8inter<string> i =NewInterimpl<string>();9I.show ("Hello");Ten  OneInter<integer> II =NewInterimpl<integer>(); AIi.show (100); - } -}

Java 16-7 generic method and generic interface (generic class similar)

Related Article

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.