Constructors
suggest changeConstructors are named after the class, have no return type, and initialize new objects. Like methods, they can take parameters. Abstract classes can have constructors too. A constructor is not itself a method.
public class Hello{
// constructor
public Hello(String wordToPrint){
printHello(wordToPrint);
}
public void printHello(String word){
System.out.println(word);
}
}
// Instantiating the object calls the constructor, which prints wordToPrint.
It is important to understand that constructors are different from methods in several ways:
- Constructors can only take the modifiers
public,private, andprotected, and cannot be declaredabstract,final,static, orsynchronized. - Constructors do not have a return type.
- Constructors MUST be named the same as the class name. In the
Helloexample, theHelloobject’s constructor name is the same as the class name. - The
thiskeyword has an additional usage inside constructors.this.method(...)calls a method on the current instance, whilethis(...)refers to another constructor in the current class with different signatures.
Constructors also can be called through inheritance using the keyword super.
public class SuperManClass{
public SuperManClass(){
// some implementation
}
// ... methods
}
public class BatmanClass extends SuperManClass{
public BatmanClass(){
super();
}
//... methods...
}
See Java Language Specification #8.8 and #15.9
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents