java create new object

www‮al.‬utturi.com
java create new object

To create a new object in Java, you can use the new operator to instantiate an object of a class.

Here is an example of how to create a new object of a class called Person:

public class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

public class Main {
    public static void main(String[] args) {
        Person person = new Person("Alice", 30);
        System.out.println(person.getName());  // prints "Alice"
        System.out.println(person.getAge());  // prints 30
    }
}

This creates a new Person object with the name "Alice" and age 30, and calls the getName and getAge methods to retrieve the values of the name and age fields.

You can also use the Class.newInstance method to create a new object of a class, but this method requires the class to have a public no-arguments constructor. For example:

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

public class Main {
    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        Class<Person> clazz = Person.class;
        Constructor<Person> constructor = clazz.getConstructor(String.class, int.class);
        Person person = constructor.newInstance("Alice", 30);
        System.out.println(person.getName());  // prints "Alice"
        System.out.println(person.getAge());  // prints 30
    }
}
Created Time:2017-11-03 00:14:52  Author:lautturi