in how many ways we can create object in java?

There are many ways to create object in java.

1)- new Keyword
Employee emp=new Employee ();
Here we are using new keyword to load the class and new operator instance a class to allocate memory for new object.

				
					public class Employee {
	public void Test() {
		System.out.println("welcome");
	}

	public static void main(String[] args) {
		Employee emp = new Employee();
		emp.Test();
	}
}
				
			

Output :- welcome

2)- forName() method of Class class and newInstance method
The forName() method of class return the class object associated with the class or interface.
In Class.forName we pass a class as a parameter String.

				
					public class Employee {
	public void Test() {
		System.out.println("welcome");
	}

	public static void main(String[] args) throws Exception {
		Employee emp = (Employee) Class.forName("com.EmployeeObject").newInstance();
		emp.Test();
	}
}
				
			

Output :- welcome

3)- By Creating a clone of Object
The clone() method can be called on an instance of the class to clone.here we pass one class state into another reference of the class.

				
					public class Employee {
	public void Test() {
		System.out.println("welcome");
	}

	public static void main(String[] args) throws CloneNotSupportedException {
		Employee emp = new Employee();
		Employee emp1 = (Employee) emp.clone();
		emp1.Test();
	}
}

				
			

Output:- welcome

4)- By De-serializing a input stream into object
ObjectInputStream ois= new ObjectInputStream(anInputStream);
Employee obj  = (Employee )ois.readObject();
here object is actually created from the serialized form of the object available as input stream.

Leave a Comment

Your email address will not be published. Required fields are marked *