Table of Contents
How objects of a class in Java is created?
We have basically four ways to create objects in Java. Although technically speaking, only one method uses the new keyword explicitly. The other methods internally use the new keyword.
- Using the new keyword: This is the most common method of object creation, It follows the following syntax:
Test obj = new Test ();
This creates an object named ‘obj’ of the Test class.
- Using Class.forName (String className) method: Java has a pre-defined class in the java.lang package called Class. The forName (String className) method in Java returns the object of a class that is linked with the bounded string name. A legitimate and fully accepted name has to be given for the class. The new Instance () method will thereafter return the instance of the given class which is the object of the class.
//Creating an object of the public class called Test //Let us assume that the Test package is present in the ‘com.p1’ package. Test obj = (Test) Class.forName (“com.p1.Test”).newInstance();
- Using clone () method: Cloning an object is the phenomenon of copying an object. This method is part of the Object Class.
//Creating an object of the class Test Test obj = new Test (); //Cloning the object created above Test obj2 = (Test) obj.clone ();
- Deserialization: The process of reading an object from the ‘saved state in a file’ is called De-serialization.
FileInputStream file = new FileInputStream (filename); ObjectIinputStream in = new ObjectInputStream (file); Object obj = in.readObject ();
Creating Multiple Objects from one type
- As a lot of objects are used for the execution of any code, it is good programming practice to create a static reference variable and use that whenever required.
Test test = new Test ();
test = new Test (); - Sometimes in inheritance, the parent class reference variable is stored in a sub-class object.
class Animal { } class Dog extends Animal {} class Cat extends Animal {} public class Test { Animal obj = new Dog (); ob = new Cat (); }
0 Comments