What Is Object in Java with Programming Examples

In this article, we will learn what is Object in Java. We all know that Java is an Object Oriented Programming Language, which entirely relies on Objects and Classes. Any entity which has State and Behavior is known as Object. It is very important to know about OOPS concepts in order to design strong object-oriented design for Java or J2EE Web Applications.

What we will learn?

  • What is OOPS?
  • What is the difference between Procedural programming and OOPS?
  • What is an Object?
  • What are the advantages of using Software Objects
  • How to Declare, Create and Initialize an Object in Java
  • 5 Different Ways to Create an Object in Java?
  • 1. Using a new keyword
  • 2. Using newInstance() method of Class class
  • 3. Using newInstance() method of Constructor class 
  • 4. Using Object Deserialization
  • 5. Using Object Cloning – clone() method
  • java.lang.Object Class in Java
  • java.lang.Object Class Methods with Examples

What is OOPS?

Object-Oriented Programming System is the programming technique to write programs based on the real world objects. The states and behaviors of an object are represented as the member variables and methods. In OOPS programming programs are organized around objects and data rather than actions and logic.

What is the difference between Procedural programming and OOPS?

  • A procedural language is based on functions object-oriented language is based on real-world objects.
  • Procedural language gives importance to the sequence of function execution but object-oriented language gives importance on states and behaviors of the objects.
  • Procedural language exposes the data to the entire program but object-oriented language encapsulates the data.
  • Procedural language follows a top-down programming paradigm but object-oriented language follows a bottom-up programming paradigm.
  • A procedural language is complex in nature so it is difficult to modify, extend and maintain but an object-oriented language is less complex in nature so it is easier to modify, extend and maintain.
  • Procedural language provides less scope of code reuse but object-oriented language provides more scope of code reuse.
Now, you are familiar with what is OOPS and difference between OOPS and Procedural Programming. 

Now let's discuss what is Object, how to use Object and what are benefits of using Objects in Java.

Let's get started with what is an object in Java with real-world examples.

What is an Object?

The Object is the real-time entity having some state and behavior. In Java, Object is an instance of the class having the instance variables as the state of the object and the methods as the behavior of the object. The object of a class can be created by using the new keyword in Java Programming language.
A class is a template or blueprint from which objects are created. So, an object is the instance(result) of a class.
I found various Object Definitions:
1. An object is a real-world entity.
2. An object is a runtime entity.
3. The object is an entity which has state and behavior.
4. The object is an instance of a class.

Real-world examples

  • Dogs have state (name, color, breed, hungry) and behavior (barking, fetching, wagging tail). Chair, Bike, Marker, Pen, Table, Car, Book, Apple, Bag etc. It can be physical or logical (tangible and intangible).
  • Bicycles also have state (current gear, current pedal cadence, current speed) and behavior (changing gear, changing pedal cadence, applying brakes).

What are the advantages of using Software Objects

Bundling code into individual software objects provides a number of benefits, including:

Modularity: The source code for an object can be written and maintained independently of the source code for other objects. Once created, an object can be easily passed around inside the system.

Information-hiding: By interacting only with an object's methods, the details of its internal implementation remain hidden from the outside world.

Code re-use: If an object already exists (perhaps written by another software developer), you can use that object in your program. This allows specialists to implement/test/debug complex, task-specific objects, which you can then trust to run in your own code.

Pluggability and debugging ease: If a particular object turns out to be problematic, you can simply remove it from your application and plug in a different object as its replacement. This is analogous to fixing mechanical problems in the real world. If a bolt breaks, you replace it, not the entire machine.

How to Declare, Create and Initialize an Object in Java

A class is a blueprint for Object, you can create an object from a class. Let's take Student class and try to create Java object for it.

Let's create a simple Student class which has name and college fields. Let's write a program to create declare, create and initialize a Student object in Java.
package net.javaguides.corejava.oops;

public class Student {
    private String name;
    private String college;

    public Student(String name, String college) {
        super();
        this.name = name;
        this.college = college;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    public String getCollege() {
        return college;
    }

    public void setCollege(String college) {
        this.college = college;
    }

    public static void main(String[] args) {

        Student student = new Student("Ramesh", "BVB");
        Student student2 = new Student("Prakash", "GEC");
        Student student3 = new Student("Pramod", "IIT");
    }
}
From the above program, the Student objects are:
Student student = new Student("Ramesh", "BVB");
Student student2 = new Student("Prakash", "GEC");
Student student3 = new Student("Pramod", "IIT");
Each of these statements has three parts (discussed in detail below):
Declaration: The code Student student; declarations that associate a variable name with an object type. 
Instantiation: The new keyword is a Java operator that creates the object.
Initialization: The new operator is followed by a call to a constructor, which initializes the new object.

Declaring a Variable to Refer to an Object

General syntax:
type name;
This notifies the compiler that you will use a name to refer to data whose type is a type. With a primitive variable, this declaration also reserves the proper amount of memory for the variable.
From the above program, we can declare variables to refer to an object as:
Student student;
Student student2;
Student student3;

Instantiating a Class

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.
For example:
Student student = new Student("Ramesh", "BVB");
Student student2 = new Student("Prakash", "GEC");
Student student3 = new Student("Pramod", "IIT");
Note that we have used a new keyword to create Student objects.

Initializing an Object

The new keyword is followed by a call to a constructor, which initializes the new object. For example:
Student student = new Student("Ramesh", "BVB");
Student student2 = new Student("Prakash", "GEC");
Student student3 = new Student("Pramod", "IIT");
From above code will call below constructor in Student class.
public class Student {
    private String name;
    private String college;

    public Student(String name, String college) {
         super();
         this.name = name;
         this.college = college;
    }
}

Different Ways to Create an Object in Java?

1. Using a new keyword

This is the most popular way of creating an object in Java using a new keyword. This approach every Java Developer knows.
package net.javaguides.corejava.oops;

public class Student {
    private String name;
    private String college;

    public Student(String name, String college) {
        super();
        this.name = name;
        this.college = college;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    public String getCollege() {
        return college;
    }

    public void setCollege(String college) {
        this.college = college;
    }

    public static void main(String[] args) {

        Student student = new Student("Ramesh", "BVB");
        Student student2 = new Student("Prakash", "GEC");
        Student student3 = new Student("Pramod", "IIT");
    }
}
From the above code, we are creating Student object using new keyword:
Student student = new Student("Ramesh", "BVB");
Student student2 = new Student("Prakash", "GEC");
Student student3 = new Student("Pramod", "IIT");

2. Using newInstance() method of Class class

Class.forName() will load the class dynamically and it indirectly will give you “Class class” object. Once the class is loaded we will be using newInstance() method to create the object dynamically.
Let's create a Java object for the Student class here:
package net.javaguides.corejava.oops;

public class Student {
    private String name = "Ramesh";
    private String college = "ABC";

    public Student() {
        super();
    }

    public Student(String name, String college) {
        super();
        this.name = name;
        this.college = college;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCollege() {
        return college;
    }

    public void setCollege(String college) {
        this.college = college;
    }

    public static void main(String[] args) {
        try {

            String className = "net.javaguides.corejava.oops.Student";
            Class clasz = Class.forName(className);
            Student student = (Student) clasz.newInstance();
            System.out.println(student.getName());
            System.out.println(student.getCollege());

        } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
Output:
Ramesh
ABC
The forName() method returns the Class object associated with the class or interfaces with the given string name.
Class clasz = Class.forName(className);
newInstance() method creates a new instance of the class represented by this Class object.
Student student = (Student) clasz.newInstance();
System.out.println(student);

3. Using newInstance() method of Constructor class 

Similar to the newInstance() method of Class class, There is one newInstance() method in the java.lang.reflect.Constructor class which we can use to create objects. We can also call a parameterized constructor, and private constructor by using this newInstance() method.
Let's demonstrate this approach by creating Student class object using newInstance() method of java.lang.reflect.Constructor class:
package net.javaguides.corejava.oops;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class Student {
    private String name = "Ramesh";
    private String college = "ABC";

    public Student() {
        super();
    }

    public Student(String name, String college) {
        super();
        this.name = name;
        this.college = college;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCollege() {
        return college;
    }

    public void setCollege(String college) {
        this.college = college;
    }

    public static void main(String args[]) {
        Constructor < Student > constructor;
        try {
            constructor = Student.class.getConstructor();
            Student student = constructor.newInstance();
            System.out.println(student.getName());
            System.out.println(student.getCollege());
        } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException |
            NoSuchMethodException | SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}
Output:
Ramesh
ABC

4. Using Object Deserialization

In this approach, we will be using Serializable interface in Java which is a marker interface(interface with no fields or methods within it) for serializing a Java Student Object s1 into a text file (sample.txt) and using object deserialization we will be reading and assigning it to a new Student object s2.
package net.javaguides.corejava.oops;

import java.io.Serializable;

public class Student implements Serializable{
    private String name;
    private String college;

    public Student() {
         super();
    }

    public Student(String name, String college) {
         super();
         this.name = name;
         this.college = college;
    }

    public String getName() {
         return name;
    }

    public void setName(String name) {
         this.name = name;
    }

    public String getCollege() {
         return college;
    }

    public void setCollege(String college) {
         this.college = college;
    }
}
package net.javaguides.corejava.oops;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class StudentDemo {
    public static void main(String[] args) {
        // Path to store the Serialized object
        String filePath = "sample.txt";
        Student s1 = new Student("Ramesh", "ABC");
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(filePath);
            ObjectOutputStream outputStream = new ObjectOutputStream(fileOutputStream);
            outputStream.writeObject(s1);
            outputStream.flush();
            outputStream.close();

            FileInputStream fileInputStream = new FileInputStream(filePath);
            ObjectInputStream inputStream = new ObjectInputStream(fileInputStream);
            Student s2 = (Student) inputStream.readObject();

            inputStream.close();

            System.out.println(s2.getName());
            System.out.println(s2.getCollege());
        } catch (Exception ee) {
            ee.printStackTrace();
        }
    }
}
Output:
Ramesh
ABC

5. Using Object Cloning – clone() method

The clone() method is used to create a copy of an existing object, in order to the clone() method the corresponding class should have implemented a Cloneable interface which is again a Marker Interface. 
In this approach we will be creating an object for Student class “student1” and using clone() method we will be cloning it to “student2” object
package net.javaguides.corejava.oops;

import java.io.Serializable;

public class Student implements Cloneable {
    private String name;
    private String college;

    public Student() {
        super();
    }

    public Student(String name, String college) {
        super();
        this.name = name;
        this.college = college;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCollege() {
        return college;
    }

    public void setCollege(String college) {
        this.college = college;
    }

    public static void main(String args[]) {
        Student student1 = new Student("Ramesh", "ABC");
        try {
            Student student2 = (Student) student1.clone();
            System.out.println(student2.getName());
            System.out.println(student2.getCollege());
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
    }
}
Output:
Ramesh
ABC

java.lang.Object Class in Java

The Object class, in the java.lang package sits at the top of the class hierarchy tree. Every class is a descendant, direct or indirect, of the Object class. Every class you use or write inherits the instance methods of Object. You need not to use any of these methods, but, if you choose to do so, you may need to override them with code that is specific to your class.

Object Class Methods

  1. protected Object clone()
  2. boolean equals(Object obj)
  3. protected void finalize()
  4. Class<?> getClass()
  5. int hashCode()
  6. void notify()
  7. void notifyAll()
  8. void wait()
  9. String toString()
The notify, notifyAll, and wait methods of Object all play a part in synchronizing the activities of independently running threads in a program. There are five of these methods:
  • public final void notify()
  • public final void notifyAll()
  • public final void wait()
  • public final void wait(long timeout)
  • public final void wait(long timeout, int nanos)
The below diagram is an Object class diagram shows a list of methods it provides.
Object Class Methods in Java with Examples

Let's discuss above each method with examples.

I have written a separate article about java.lang.Object class methods so check out java.lang.Object class methods with examples article.

References

Object Class Methods in Java with Examples
http://www.javaguides.net/p/java-tutorial-learn-java-programming.html
https://docs.oracle.com/javase/tutorial/java/javaOO/objectcreation.html

Comments

  1. marker interface(method with no body)

    This needs a correction. Marker interface is an interface without any method or field.

    ReplyDelete

Post a Comment