Sub topic 3
Accept Variable Numbers of Arguments
A variable-length argument list, or varargs, lets a method accept any number of values of the same type. Write the type followed by three dots, as in int... values. Inside the method, values is an array, or ordered group of values. A varargs parameter must be the last parameter.
Save this example as FeatureDemo.java. The sections below explain the other features it uses.
class NegativeValueException extends Exception {}
class Animal {
String sound() {
return "sound";
}
}
class Dog extends Animal {
@Override
String sound() {
return "woof";
}
}
class FeatureDemo {
static int sum(int... values) throws NegativeValueException {
int total = 0;
for (int value : values) {
if (value < 0) {
throw new NegativeValueException();
}
total += value;
}
return total;
}
static int factorial(int n) {
if (n == 0) {
return 1;
}
return n * factorial(n - 1);
}
static <T> T echo(T value) {
return value;
}
public static void main(String[] args) {
try {
System.out.println(sum(2, 3, 4));
System.out.println(sum(-1));
} catch (NegativeValueException e) {
System.out.println("Negative value");
}
System.out.println(factorial(3));
Animal animal = new Dog();
System.out.println(animal.sound());
System.out.println(echo("Java"));
}
}Compile and run it:
javac FeatureDemo.java
java FeatureDemoThe output is 9, Negative value, 6, woof, and Java, each on its own line.
Handle and Declare Exceptions
An exception is a signal that something went wrong. The sum method uses throw to raise one for a negative value. Its throws clause declares that this can happen.
Here, the exception is checked: Java requires the caller to catch it or declare it. The try and catch blocks handle it.
Write Methods That Call Themselves
Recursion is when a method calls itself. factorial(3) calculates 3 * 2 * 1. The base case, n == 0, stops the calls. Each call moves closer to that case.
Override Instance Methods
A subclass is a class based on another class. Dog is a subclass of Animal. It overrides, or replaces, the inherited sound method. The @Override marker asks Java to check that the method overrides another one.
Write Generic Methods
A generic method works with different types. In echo, T is a type parameter: a placeholder for a reference type. Java chooses String when the example passes "Java".
Design Clear Method Contracts
A method contract describes allowed inputs, results, and errors. For example, sum accepts zero or more nonnegative integers and returns zero for no arguments. It throws an exception for a negative input. Its result can overflow if the total is too large for int. Use factorial only with values from 0 through 12.
Exercise
What does sum() return, and what happens when sum(-2) is called?
Show answer
sum() returns 0. sum(-2) throws NegativeValueException.