Helper Class
class MyHelperClass {
public double discount;
public MyHelperClass(double discount) {
if (discount > 0 && discount < 1) {
this.discount = discount;
}
}
public double discountedPrice(double price) {
return price - (price * discount);
}
}
Utility Class
- only contain static methods
- We declare class as
final
- We do not mark the class
abstract since it will indicate that someone will want to extend it
- We do not use
interface as utility class since it can be implemented, and it is not possible to have final interface
- It is sometimes stateless without static fields
- It cannot be instantiated, hence we write a private constructor
- generally named plural
- Examples:
Arrays
Collections
Objects
Streams
Collectors
Comparators (from Spring framework, not java.util)
Executors
- https://stackoverflow.com/questions/32375149/is-it-mandatory-utility-class-should-be-final-and-private-constructor
public final class StringUtils {
private StringUtils() {}
public static String toUpperCase(String str) {
return str.toUpperCase();
}
}