Constructor
Tips:
if super or this are called, they can only be called on the first line of the constructor
An Exception can be thrown if a parameter is invalid
You should ensure that the constructed object is in a valid state
Constructors should never call an overridable method (an overridable method is one which is neither private, static, nor final)
Constructors are never synchronized or static.
Constructors can be private, in order to restrict construction
Private constructors
–classes containing only constants
–type safe enumerations
–singletons
Static factory
Static factory methods have names
Static factory methods can improve performance
Restrict the numbers of object creation
Interface-based return value
public class StaticFactory {
private static final StaticFactory INSTANCE = new StaticFactory();
private StaticFactory() {
}
public static StaticFactory getInstance(){
return INSTANCE;
}
}
Clone
Clone() is protected
Implement Cloneable interface
Overridden protected Object clone() throws CloneNotSupportedException
Invoke super.clone() in your clone() method
Catch possible exception
public class CloneExample implements Cloneable
{
.....
protected Object clone()
{
try{
return super.clone();
} catch (CloneNotSupportedException e) {
throw new Error(
"This should not occur since we implement Cloneable");
}
}
}
Use public clone() to override parent’s clone()
No need to invoke constructor in clone method
Inheritance hierarchy considerations
Final variable doesn’t work for some clone()’s implementation
Should not invoke any non-final method in clone()
Final class
Copy Constructor
