- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Bounded types with generics in Java
There may be times when you'll want to restrict the kinds of types that are allowed to be passed to a type parameter. For example, a method that operates on numbers might only want to accept instances of Number or its subclasses. This is what bounded type parameters are for.
To declare a bounded type parameter, list the type parameter's name, followed by the extends keyword, followed by its upper bound.
Example
Following example illustrates how extends is used in a general sense to mean either "extend" (as in classes) or "implements" (as in interfaces). This example is a Generic method to return the largest of three Comparable objects −
public class MaximumTest { // determines the largest of three Comparable objects public static <T extends Comparable<T>> T maximum(T x, T y, T z) { T max = x; // assume x is initially the largest if(y.compareTo(max) > 0) { max = y; // y is the largest so far } if(z.compareTo(max) > 0) { max = z; // z is the largest now } return max; // returns the largest object } public static void main(String args[]) { System.out.printf("Max of %d, %d and %d is %d
",3, 4, 5, maximum( 3, 4, 5 )); System.out.printf("Max of %.1f,%.1f and %.1f is %.1f
",6.6, 8.8, 7.7, maximum( 6.6, 8.8, 7.7 )); System.out.printf("Max of %s, %s and %s is %s
","pear","apple", "orange", maximum("pear", "apple", "orange")); } }
This will produce the following result −
Output
Max of 3, 4 and 5 is 5 Max of 6.6,8.8 and 7.7 is 8.8 Max of pear, apple and orange is pear
- Related Articles
- Bounded-types in generics in Java?
- What are upper-bounded wildcard w.r.t Generics method in Java?
- What are lower-bounded wildcard w.r.t Generics method in Java?
- What are raw types in generics in Java?
- Generics in Java
- How to use method references with Generics in Java?
- What is Java Generics?
- Templates in C++ vs Generics in Java
- Why do we need generics in Java?
- Generics vs non-generics in C#
- What are wildcards arguments in Generics In Java?
- Number of Subarrays with Bounded Maximum in C++
- What are Unbounded wildcard w.r.t Generics method in Java?
- Generics in C#
- Generics in Golang

Advertisements