Thursday, November 7, 2019

What is Java Object:

What is Java Object?

A Java object is a combination of data and procedures working on the available data. An object has a state and behavior. The state of an object is stored in fields (variables), while methods (functions) display the object's behavior. Objects are created from templates known as classes. 

An object has three main features

  • State: refers the data (value) of an object.
  • Behavior: refers the behavior (functionality) of an object such as playing cricket, dancing, etc.
  • Identity: An object identity is a unique ID. The value of the ID is not visible to the external user. However, it is used internally by the JVM to identify each object uniquely.
An object e.g., cow, car, table, TV, CD, DVD, etc. It can be physical or logical (tangible and intangible). The example of an intangible object is online reservation system.
                                                        
Note :

An object is a software bundle of variables and related methods.You can show real-world objects using software objects. If you want to represent real-world Cat as software objects in an animation program.
For example, an event is a common object used in GUI window systems to represent the action of a user pressing a F5 button for refresh on keyboard.



Methods of creating objects in Java

These are some ways in which you can create objects in Java:

     1)    By Using new Keyword : 

Using new keyword is the most basic way to create an object. This is the most common way to create an object in java.By using this method we can call any constructor.


public class NewKeyword 
{
    String name = "Amit Dhiman";
    public static void main(String[] args) 
    {
       
        NewKeyword obj = new NewKeyword();//creating object
        System.out.println(obj.name);
    }
}
Output:
Amit Dhiman


2)    By Using New Instance : 

We can create an object –Class.forName. We can use it to create the Object of a Class. Class. forName actually 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.


public class NewInstance
{
    String name = "Amit Dhiman";
    public static void main(String[] args)
    {
        try
        {
            Class cls = Class.forName("NewInstanceExample");
            NewInstanceExample obj =
                    (NewInstanceExample) cls.newInstance();
            System.out.println(obj.name);
        }
        catch (ClassNotFoundException e)
        {
            e.printStackTrace();
        }
        catch (InstantiationException e)
        {
            e.printStackTrace();
        }
        catch (IllegalAccessException e)
        {
            e.printStackTrace();
        }
    }
}
Output:
Amit Dhiman

     3)    Using clone() method: 

Whenever clone() is called on any object, the JVM actually 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 clone() method on an object we need to implement Cloneable and define the clone() method in it.


public class Clone implements Cloneable
{
    @Override
    protected Object clone() throws CloneNotSupportedException
    {
        return super.clone();
    }
    String name = "Amit Dhiman";

    public static void main(String[] args)
    {
        Clone obj1 = new Clone();
        try
        {
            Clone obj2 = (Clone) obj1.clone();
            System.out.println(obj2.name);
        }
        catch (CloneNotSupportedException e)
        {
            e.printStackTrace();
        }
    }
}
Output:
Amit Dhiman


Note :
·         Here we are creating the clone of an existing Object and not any new Object.
·         Class need to implement Cloneable Interface otherwise it will throw CloneNotSupportedException.

       4)    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.

Serializing an Object :


import java.io.*;

public class Deserialization implements Serializable
{
    private String name;
    Deserialization(String name)
    {
        this.name = name;
    }

    public static void main(String[] args)
    {
        try
        {
            Deserialization d =
                    new Deserialization("Amit Dhiman");
            FileOutputStream f = new FileOutputStream("file.txt");
            ObjectOutputStream oos = new ObjectOutputStream(f);
            oos.writeObject(d);
            oos.close();
            f.close();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}
Object of DeserializationExample class is serialized using writeObject() method and written to file.txt file.

Deserialization of Object :


import java.io.*;

public class Deserialization
{
    public static void main(String[] args)
    {
        try
        {
            Deserialization d;
            FileInputStream f = new FileInputStream("file.txt");
            ObjectInputStream oos = new ObjectInputStream(f);
            d = (Deserialization)oos.readObject();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        System.out.println(d.name);
    }
}
Output:
Amit Dhiman

    5)    Using newInstance() method of 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. In fact newInstance() method of Class internally uses newInstance() method of Constructor class.


import java.lang.reflect.*;

public class Reflection
{
    private String name;
    Reflection()
    {
    }
    public void setName(String name)
    {
        this.name = name;
    }
    public static void main(String[] args)
    {
        try
        {
            Constructor<Reflection> constructor
                = Reflection.class.getDeclaredConstructor();
            Reflection r = constructor.newInstance();
            r.setName("Amit Dhiman");
            System.out.println(r.name);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}
Output:
Amit Dhiman

No comments:

Post a Comment