Skip to content

Commit feed9d4

Browse files
committed
Updated code with comments for the generic examples
1 parent d2fd8ed commit feed9d4

6 files changed

Lines changed: 13 additions & 1 deletion

File tree

0 Bytes
Binary file not shown.
0 Bytes
Binary file not shown.
0 Bytes
Binary file not shown.
0 Bytes
Binary file not shown.

‎JavaGenericsExamples/src/CalculatorExample1/CalcExample1.java‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
11
package CalculatorExample1;
22

3+
4+
// This is a naive implementation of a calculator class without generics.
5+
// Note here that we're only able to take integers.
6+
// What if we want to pass in a double or a pair of doubles?
7+
38
class Calc {
49
public int add(int a, int b) {
510
return a+b;

‎JavaGenericsExamples/src/CalculatorExample1/CalcExample2.java‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
package CalculatorExample1;
22

3-
3+
// Here we are using the concepts of generics to be able to pass in any given
4+
// type (as long as it inherits from the Number superclass). This will also return
5+
// a double, however, we could also return a type <T> which, again, is defined at
6+
// compile time.
47

58
class MyCalc <T extends Number> {
69
public double add(T a, T b) {
@@ -25,6 +28,10 @@ public double div (T a, T b) {
2528
public class CalcExample2 {
2629
public static void main(String args[]) {
2730
MyCalc c = new MyCalc();
31+
32+
// Here we can freely pass in any derived class of number without
33+
// having to write a new method for each parameter signature.
34+
2835
Double result = c.add(new Integer(1),new Double(1.0));
2936
System.out.println("result = " + result);
3037

0 commit comments

Comments
 (0)