Objects in java

Object is the basic unit of Object-Oriented Programming and represents real-life entities.  An object consists of state, behavior, and identity

> The state is represented by the attributes of an object. It also reflects the properties of an object.

> Behavior is represented by the methods of an object. It also reflects the response of an object with other objects.

> Identity gives a unique name to an object and enables one object to interact with other objects.

There are three steps when creating an object −

> Declaration 

> Instantiation 

> Initialization

Declaring Objects

A variable declaration with a variable name with an object type.

This notifies the compiler that you will use name to refer to data whose type is type and it reserves a proper memory for the variable

  ClassName ReferenceVariable = new ClassName();

Instantiating an object

The 'new' keyword is used to create the object The new operator instantiates a class by allocating memory for a new object and returning a reference to that memory. The new operator also invokes the object constructor

Initializing an object

The 'new' keyword is followed by a call to a constructor. This call initializes the new object.

Different Ways to create an object

Using new Keyword

This is the most basic and commonly used method to create an object.

Example:

public class MyExample {
       String name="java tutorial";
       public static void main(String[]args){
       // Here we are creating Object of 
       // MyExample using new keyword
       MyExample obj=new MyExample();
       System.out.println(obj.name);
       }
}
 
Here MyExample class is instantiated as obj and obj.name brings out the name of the class

Using New Instance

If we know the name of the class & if it has a public default constructor we can create an object –Class.forName. We can use it to create the Object of a Class. Class.forName loads the Class in Java but doesn’t create any Object. To create an Object of the Class you have to use the new Instance Method of the Class.

Example:

public class MyExample {
    String name = "java tutorial";
    public static void main(String[] args) {
        // Here we are creating Object of 
        // MyExample using new keyword
        try {
            Class cls = Class.forName("MyExample");
            MyExample obj =
                    (MyExample) cls.newInstance();
            System.out.println(obj.name);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}

 

Using clone() method

Whenever clone() is called on any object, the JVM creates a new object and copies all content of the previous object into it. Creating an object using the clone method does not invoke any constructor.
To use the clone() method on an object we need to implement Cloneable and define the clone() method in it.

Example:

public class CloneSample implements Cloneable {
    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
    String name = "Javatutorial";
    public static void main(String[] args) {
        CloneSample obj1 = new CloneSample();
        try {
            CloneSample obj2 = (CloneSample) obj1.clone();
            System.out.println(obj2.name);
        }
        catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
    }
}

 

Instance obj1 is cloned to obj2

The clone method is declared protected in the Object class. So it can be accessed only in a subclass or in the same package. That is the reason why it has been overridden here in Class.

A class needs to implement Cloneable Interface otherwise it will throw CloneNotSupportedException.

Using deserialization

 Whenever we serialize and then deserialize an object, JVM creates a separate object. In deserialization, JVM doesn’t use any constructor to create the object.
To deserialize an object we need to implement the Serializable interface in the class.

Example:

import java.io.*;
public class DeserializationExample {
    public static void main(String[] args) {
        try {
            DeserializationExample d;
            FileInputStream f = new FileInputStream("file.txt");
            ObjectInputStream oos = new ObjectInputStream(f);
            d = (DeserializationExample) oos.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(d.name);
    }
}

 

Using the newInstance() method of the Constructor class

This is similar to the newInstance() method of a class. There is one newInstance() method in the java.lang.reflect.Constructor class which we can use to create objects. It can also call parameterized constructor, and private constructor by using this newInstance() method.

Both newInstance() methods are known as reflective ways to create objects. The NewInstance () method of Class internally uses the newInstance() method of the Constructor class.

Example:

import java.lang.reflect.*;
public class ReflectionExample {
    private String name;
    ReflectionExample() {
    }
    public void setName(String name) {
        this.name = name;
    }
    public static void main(String[] args) {
        try {
            Constructor constructor
                    = ReflectionExample.class.getDeclaredConstructor();
            ReflectionExample r = constructor.newInstance();
            r.setName("Javatutorial");
            System.out.println(r.name);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 

Related Tutorials

Map