Java Object Creation By New Keyword

The new Keyword is java is the simplest way of creating the object. The new keyword calls the default or parameterized constructor of the class depending on the parameters.

package org.wesome.dsalgo.design.pattern;

public class Apple {
    String name = "McIntosh";

    public static void main(String[] args) {
        Apple apple = new Apple();
        System.out.println("apple = " + apple.name);
    }
}

 

The new Keyword can create a new object by calling the default constructor or parameterized constructor depending upon the parameters passed.
 

package org.wesome.dsalgo.design.pattern;

public class Apple {
    String name = "McIntosh";

    public Apple() {
        System.out.println("Apple default constructor");
    }

    public Apple(String name) {
        System.out.println("Apple parameterized constructor");
        this.name = name;
    }

    public static void main(String[] args) {
        Apple mcIntoshApple = new Apple();
        System.out.println("apple = " + mcIntoshApple.name);
        Apple fujiApple = new Apple("Fuji");
        System.out.println("apple = " + fujiApple.name);
    }
}

 

New Keyword with Exception

The new keyword by default calls the default constructor of the class, if the constructor throws an Exception while creating an object, the new keyword will fail, which is not the case with the newInstance method.
 

 

package org.wesome.dsalgo.design.pattern;

public class Apple {
    String name = "McIntosh";

    public Apple() {
        System.out.println("Apple default constructor");
        throw new RuntimeException();
    }

    public static void main(String[] args) {
        Apple apple = new Apple();
        System.out.println("apple = " + apple.name);
    }
}

 

follow us on