How is object created in java?

Answer Posted / chantiraji

There are FIVE different ways to create objects in Java:

1. Using `new` keyword:

This is the most common way to create an object in Java. Almost 99% of objects are created in this way.

MyObject object = new MyObject();//normal way
2. By Using Factory Method:

ClassName ObgRef=ClassName.FactoryMethod();
Example:

RunTime rt=Runtime.getRunTime();//Static Factory Method
3. By Using Cloning Concept:

By using clone(), the clone() can be used to create a copy of an existing object.

MyObjectName anotherObject = new MyObjectName();
MyObjectName object = anotherObjectName.clone();//cloning Object
4. Using `Class.forName()`:

If we know the name of the class & if it has a public default constructor we can create an object in this way.

MyObjectName object = (MyObjectNmae) Class.forName("PackageName.ClassName").newInstance();
Example:

String st=(String)Class.forName("java.lang.String").newInstance();
5. Using object deserialization:

Object deserialization is nothing but creating an object from its serialized form.

ObjectInputStreamName inStream = new ObjectInputStreamName(anInputStream );
MyObjectName object = (MyObjectNmae) inStream.readObject();

Is This Answer Correct ?    2 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

What is the vector class in java programming?

790


Is minecraft java edition free?

876


Why collection is called framework in java?

747


What is the purpose of checked and unchecked exceptions in JAVA?

805


What is the difference between actual and formal parameters?

726


What are the differences between c++ and java?

837


What is the purpose of garbage collection in java, and when is it used?

812


Can final class have constructor?

715


Why does java have different data types for integers and floating-point values?

786


What is the current version of java?

786


Difference between collection, collection and collections in java?

815


Write a program to show whether a graph is a tree or not using adjacency matrix.

867


What are desktop procedures?

810


List some java keywords sun like c, c + + keywords?

807


What is a lock or purpose of locks in java?

814