Short answer: No.
Fortunately, you can simulate them.
- use method overloading
- allow nulls as an input
- declare a method with Java Varargs
To know how to do those, check :
http://dolszewski.com/java/java-default-parameters/
// Foo.java
public class Foo {
// For a constructor
public Foo() { this(4); }
public Foo(int x) {
System.out.println("Initializing Foo with " + x + ".");
}
// For a method
public void identifyString() { identifyString("Grepper is cool!"); }
public void identifyString(String source) {
int length = source.length();
if (length < 0)
System.out.println("what the heck");
else if (length == 0)
System.out.println("Source is empty!");
else if (length == 1)
System.out.println("Source is a char!");
else
System.out.println("Source is a String!");
}
}
// Main.java
public class Mainf {
public static void main(String[] args) {
Foo foo = new Foo();
foo.identifyString();
}
}
/* OUTPUT:
Initializing Foo with 4.
Source is a string!
*/
No, the structure you found is how Java handles it (that is, with overloading instead of default parameters).
For constructors, See Effective Java: Programming Language Guide's Item 1 tip (Consider static factory methods instead of constructors) if the overloading is getting complicated. For other methods, renaming some cases or using a parameter object can help. This is when you have enough complexity that differentiating is difficult. A definite case is where you have to differentiate using the order of parameters, not just number and type.