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
What are the restriction imposed on a static method or a static block of code?
What is the history of java?
What happens if we override private method?
What are different type of exceptions in java?
What is meant by null and void?
What do you mean by of string::valueof expression in java 8?
Can a constructor be protected?
Why there is no call by reference in java?
Define how does a try statement determine which catch clause should be used to handle an exception?
Why is logger singleton?
What is the purpose of the wait(), notify(), and notifyall() methods in java programming?
Explain the selection sort algorithm and state its time complexity?
When do we use synchronized blocks and advantages of using synchronized blocks?
What does a boolean method return?
Can we compare two strings in java?