JVM / Java / OOP / Constructors
1. Multiple constructors
package oop.constructors;
public class MultipleConstructors {
public static void main(String[] args) {
new A();
new A("aaa");
new A(100);
}
}
class A {
public A() {
System.out.println("Default constructor used");
}
public A(String s) {
System.out.println("Constructor 1 used: " + s);
}
public A(int n) {
System.out.println("Constructor 2 used: " + n);
}
}
2. This method
To call another constructor from the same class use this() method.
package oop.constructors;
public class ThisMethod {
public static void main(String[] args) {
Rectangle a = new Rectangle();
Rectangle b = new Rectangle(100, 200);
Rectangle c = new Rectangle(300, 400, 11, 22);
System.out.println(a);
System.out.println(b);
System.out.println(c);
}
}
class Rectangle {
private int x, y;
private int width, height;
public Rectangle() {
this(0, 0, 0, 0);
}
public Rectangle(int width, int height) {
this.width = width;
this.height = height;
}
public Rectangle(int width, int height, int x, int y) {
this(width, height);
this.x = x;
this.y = y;
}
public String toString() {
return String.format(
"W: %s H: %s x: %s y: %s", width, height, x, y
);
}
}
3. Super method
The super() method is used to call parent constructor.
Constructor call must be the first statement in a controller.
package oop.constructors;
public class SuperMethod {
public static void main(String[] args) {
new MainClass();
}
}
class BaseClass {
public BaseClass() {
System.out.println("Parent constructor called.");
}
}
class MainClass extends BaseClass {
public MainClass() {
super();
}
}