Constructors have the same name as the class they initialize.
Body ()
{
idNum = nextID++;
}
Move the responsibility for idNum inside the Body class.
Body sun = new Body(); // idNum is 0
Body earth = new Body(); // idNum is 1
Constructors can take zero or more parameters.
Constructors have no return type.
Constructors are invoked after the instance variables of the new object have been assigned their default initial values, and after their explicit initializers are executed.
The following three classes demonstrate how constructors are called for classes and superclasses.
public class ParentClass {
public ParentClass() {
System.out.println( "ParentClass constructor was called" );
}
}
public class ChildClass extends ParentClass {
public ChildClass() {
System.out.println( "ChildClass constructor was called" );
}
}
public class Main {
public static void main(String[] args) {
ChildClass cc = new ChildClass();
}
}