coderz.py

Keep Coding Keep Cheering!

Java object creation methods

method overloading and method overriding

Everything revolves around the object in Java, which is an object-oriented language. An object represents a class’s runtime entity and is required to call the class’s variables and methods.

A Java object is a member of a Java class (also known as an instance). There is an identity, a behavior, and a state for each object. Fields (variables) store an object’s state, while methods (functions) display the object’s behavior. Templates, also known as classes, are used to create objects at runtime.

To create an object, Java provides various ways:
  • new keyword
  • Clone method
  • Deserialization
  • newInstance() method
new Keyword:

Creating objects with the new keyword is very ubiquitous in Java. This method calls a user-defined or system-defined default constructor to initialize instance variables. The new keyword allocates memory in the heap for the newly created object.

Example:


public class Demo
{ 
    String str = "coderzpy"; 
    public static void main(String as[])  
    { 
     Demo obj = new Demo(); 
      System.out.println(obj.str); 
    } 
}

Here, we created an object obj and used it to print the class variable str.

newInstance() method:

To create a new instance of the class, use the newInstance() method of the Class and Constructor classes. The newInstance() method of the Class class can call a function Object() { [native code] } with zero arguments, whereas the newInstance() method of the Constructor class can call a function Object() { [native code] } with any number of arguments.

Example:

class Simple{  
 void message(){System.out.println("Hello Java");}  
}  
  
class Test{  
 public static void main(String args[]){  
  try{  
  Class c=Class.forName("Simple");  
  Simple s=(Simple)c.newInstance();  
  s.message();  
  
  }catch(Exception e){System.out.println(e);}  
  
 }  
}  
clone() method:

Object cloning is a technique for making an exact duplicate of an object. The Object class’s clone() method is used to duplicate an object.

The java.lang.Cloneable interface must be implemented by the class whose object clone we want to create.

class Main implements Cloneable {

  // declare variables
  String name;
  int year;
  public static void main(String[] args) {

    // create an object of Main class
    Main obj1 = new Main();

    // initialize name and version using obj1
    obj1.name = "Coderzpy";
    obj1.year = 2022;

    // print variable
    System.out.println(obj1.name);      
    System.out.println(obj1.year);    

    try {

      // create clone of obj1
      Main obj2 = (Main)obj1.clone();

      // print the variables using obj2
      System.out.println(obj2.name);      
      System.out.println(obj2.year);   
    }
    catch (Exception e) {
      System.out.println(e);
    }

  }
}
Output:
Coderzpy
2022
Coderzpy
2022

In subsequent tutorials, we will delve deeper into it.

Deserialization method:

Deserialization is the reverse process, where the byte stream is used to recreate the actual Java object in memory. This mechanism is used to persist the object. 

Example:

// Java code for serialization and deserialization
// of a Java object
import java.io.*;

class Demo implements java.io.Serializable
{
	public int a;
	public String b;

	// Default constructor
	public Demo(int a, String b)
	{
		this.a = a;
		this.b = b;
	}

}

class Test
{
	public static void main(String[] args)
	{
		Demo object = new Demo(1, "coderzpy");
		String filename = "file.ser";
		
		// Serialization
		try
		{
			//Saving of object in a file
			FileOutputStream file = new FileOutputStream(filename);
			ObjectOutputStream out = new ObjectOutputStream(file);
			
			// Method for serialization of object
			out.writeObject(object);
			
			out.close();
			file.close();
			
			System.out.println("Object has been serialized");

		}
		
		catch(IOException ex)
		{
			System.out.println("IOException is caught");
		}


		Demo object1 = null;

		// Deserialization
		try
		{
			// Reading the object from a file
			FileInputStream file = new FileInputStream(filename);
			ObjectInputStream in = new ObjectInputStream(file);
			
			// Method for deserialization of object
			object1 = (Demo)in.readObject();
			
			in.close();
			file.close();
			
			System.out.println("Object has been deserialized ");
			System.out.println("a = " + object1.a);
			System.out.println("b = " + object1.b);
		}
		
		catch(IOException ex)
		{
			System.out.println("IOException is caught");
		}
		
		catch(ClassNotFoundException ex)
		{
			System.out.println("ClassNotFoundException is caught");
		}

	}
}
Output:
Object has been serialized
Object has been deserialized 
a = 1
b = coderzpy

Note: also read about the Java Arrays

Follow Me

If you like my post please follow me to read my latest post on programming and technology.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Leave a Comment

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

Advertisement