How do I invoke superclass constructor?

This example shows you how to use the super keyword to call a superclass constructor. The Female class constructor calls its superclass constructor and initializes its own initialization parameters. The call to the superclass constructor must be done in the first line of the constructor in the subclass.

package org.kodejava.example.fundamental;

public class Human {
    private String gender;
    private int age;

    public Human(String gender) {
        this.gender = gender;
    }
}

To call a superclass constructor we call super(). In the case below we call the superclass constructor with one string variable as a parameter.

package org.kodejava.example.fundamental;

public class Female extends Human {
    private String hairStyle;

    public Female(String hairStyle, String gender) {
        super(gender);
        this.hairStyle = hairStyle;
    }
}

How do I create constructors for a class?

Every class in Java has a constructor. constructor is a method that is used to create an instance or object of the class. Every time you create an instance, you must invoke a constructor.

If you do not create a constructor method of your class, the compiler will build a default one. A default constructors is a constructor that accept no argument.

Things to be noted when you declare a constructor:

  • Constructor must have the same name as the class in which they are declared.
  • Constructor can’t have a return type.
  • Constructor can have access modifier.
  • Constructor can take arguments.
  • Constructor can’t be marked static.
  • Constructor can’t be marked final or abstract.
package org.kodejava.basic;

public class ConstructorDemo {
    private String arg;
    private int x;
    private int y;

    public ConstructorDemo() {
    }

    public ConstructorDemo(String arg) {
        this.arg = arg;
    }

    public ConstructorDemo(int x) {
        this.x = x;
    }

    public ConstructorDemo(int x, int y) {
        this.y = y;
    }
}

class RunConstructor {
    public static void main(String[] args) {
        // Change the default constructor from private to public in
        // the ConstructorDemo class above then call the statement 
        // below. It will create an instance object cons0 without 
        // any error.
        ConstructorDemo cons0 = new ConstructorDemo();

        // Change the default constructor back to private, then call 
        // the statement below. ConstructorDemo() is not visible 
        // because it declared as private.
        ConstructorDemo cons1 = new ConstructorDemo();

        // invoke Constructor(String arg)
        ConstructorDemo cons2 = new ConstructorDemo("constructor");

        // invoke public Constructor(int x)
        ConstructorDemo cons3 = new ConstructorDemo(1);

        //invoke Constructor(int x, int y)
        ConstructorDemo cons4 = new ConstructorDemo(1, 2);
    }

}

How do I define constructor in enum type?

In the following example you’ll see how to add a constructor to an enum type value. Because an enum is just another class type it can have constructors, fields and methods just like any other classes. Below we define a constructor that accept a string value of color code. Because our enum now have a new constructor declared we have to define the constant named value as RED("FF0000"), ORANGE("FFA500"), etc.

In Java enumeration expanded beyond just as a named constants. Because enum is a class type we can add methods, fields and constructors to the enum type as you can see in the example below.

package org.kodejava.basic;

public enum Rainbow {
    RED("FF0000"),
    ORANGE("FFA500"),
    YELLOW("FFFF00"),
    GREEN("008000"),
    BLUE("0000FF"),
    INDIGO("4B0082"),
    VIOLET("EE82EE");

    private final String colorCode;

    // The constructor of Rainbow enum.
    Rainbow(String colorCode) {
        this.colorCode = colorCode;
    }

    /**
     * Get the hex color code.
     *
     * @return hex color code
     */
    public String getColorCode() {
        return colorCode;
    }
}
package org.kodejava.basic;

public class EnumConstructor {
    public static void main(String[] args) {

        // To get all values of the Rainbow enum we can call the
        // Rainbow.values() method which return an array of
        // Rainbow enum values.
        for (Rainbow color : Rainbow.values()) {
            System.out.println("Color = " + color.getColorCode());
        }
    }
}

How do I create object using Constructor object?

The example below using a constructor reflection to create a string object by calling String(String) and String(StringBuilder) constructors.

package org.kodejava.lang.reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class CreateObjectDemo {
    public static void main(String[] args) {
        Class<String> clazz = String.class;

        try {
            Constructor<String> constructor = clazz.getConstructor(String.class);

            String object = constructor.newInstance("Hello World!");
            System.out.println("String = " + object);

            constructor = clazz.getConstructor(StringBuilder.class);
            object = constructor.newInstance(new StringBuilder("Hello Universe!"));
            System.out.println("String = " + object);
        } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}

How do I get constructors of a class object?

Below is an example that showing you how to get constructors of a class object. In the code below we get the constructors by calling the Class.getDeclaredConstructors() or the Class.getConstructor(Class[]) method.

package org.kodejava.lang.reflect;

import java.lang.reflect.Constructor;

public class GetConstructors {
    public static void main(String[] args) {
        Class<String> clazz = String.class;

        // Get all declared constructors and iterate the constructors to get their
        // name and parameter types.
        Constructor<?>[] constructors = clazz.getDeclaredConstructors();
        for (Constructor<?> constructor : constructors) {
            String name = constructor.getName();
            System.out.println("Constructor name= " + name);

            Class<?>[] parameterTypes = constructor.getParameterTypes();
            for (Class<?> c : parameterTypes) {
                System.out.println("Param type name = " + c.getName());
            }
            System.out.println("----------------------------------------");
        }

        // Getting a specific constructor of the java.lang.String
        try {
            Constructor<String> constructor = String.class.getConstructor(String.class);
            System.out.println("Constructor     = " + constructor.getName());
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }
}