/**
* This example demonstrates
* how to add two numbers
* using Java Generics
*
*/
public class Main {
public static void main(String[] args) {
Add<Integer> addIntegers = new AddIntegers();
System.out.println(addIntegers.add(1,2));
Add<Double> addDoubles = new AddDoubles();
System.out.println(addDoubles.add(1d,2d));
}
}
/**
* Add interface that accepts a
* generic type T with bounded
* type Number
*/
interface Add<T extends Number> {
T add(T number1, T number2);
}
/**
* Implementation of Add as
* generic Integer type
* argument
*/
class AddIntegers implements Add<Integer> {
public Integer add(Integer no1, Integer no2) {
return no1 + no2;
}
}
/**
* Implementation of Add as
* generic Double type
* argument
*/
class AddDoubles implements Add<Double> {
public Double add(Double no1, Double no2) {
return no1 + no2;
}
}
Output:
3
3.0
More Posts related to Java,
- [Fix] java.time.zone.ZoneRulesException: Unknown time-zone ID
- Parse XML file in Java using DOM Parser
- Java equals method - Tutorial
- [Program] How to read three different values using Scanner in Java
- Java: The value of the local variable string is not used
- Display Output in Java Console as a Table
- How to detect Operating System using Java code
- Java 8 Streams map() with examples
- [Fix] java: incompatible types: incompatible parameter types in lambda expression error
- Add newline character Java code example (\r \n \r\n)
- List of Java Major Minor Version Numbers
- IntelliJ Keyboard Shortcut to remove unused imports [Java]
- Java - Check if array contains the value
- [Fix] Java Exception with Lambda - Cannot invoke because object is null
- How to declare and initialize Array in Java Programming
- [Solved] com.sun.xml.ws.transport.http.servlet.WSServletContextListener ClassNotFoundException
- XmlRpcException ConnectException connection refused error
- Create a Zip file using Java Code programmatically
- List of jar files for Jax-ws (SOAP) based Java Web Services
- How to fix Java HTTP java.net.UnknownHostException
- List of jars required for Struts2 project
- [fix] java: incompatible types: double cannot be converted to java.lang.Integer Generics
- Maven BUILD FAILURE: Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin
- Get the current timestamp in Java
- java: unclosed string literal [Error]
More Posts:
- Channel 50 SMSes received every few minutes Android Phones - Android
- Fix Power BI error Access to the resource is forbidden when connecting SharePoint Online List as data source - SharePoint
- Aw Snap! Something went wrong while displaying this webpage Error code: STATUS_INVALID_IMAGE_HASH - Chrome
- PHP Warning: Cannot modify header information - headers already sent - PHP
- Top 10 emerging breakthrough trending technologies - HowTos
- How to display directory tree in Mac Terminal - MacOS
- How to hide or disable iOS 14 App Library on iPhone? - Apple
- Disable Chrome Notification bell from Mac OS X menu bar - Mac-OS-X