Classes and Objects in Java – Fundamentals of OOPs

Java is an object-oriented programming language. You should be familiar with Class and Object in Java to design your code. Java classes and objects are fundamental concepts. Here, classes are user-defined datatypes and objects are an instance of a class.

There are many things which you don’t know about Java Classes and Objects. Let’s learn them together!

Class and Object in Java

Java Classes are user-defined data type from which the objects are created.

Java Objects are the basic entity, they are linked by classes and methods.

1. Java Class

A class is a blueprint or we can say it is a user-defined datatype in which we can specify member functions and declare member variables. These variables in Java are known as ‘instances’ of classes which actually are the ‘objects’.

The components of the Java class declaration are-

  • Class Modifiers – The access of a java class can define. For example, it can public or can a default access modifiers.

Recommended Reading – Access Modifiers in Java

  • Class Name –  The class name in java should begin with an initial letter, which by convention should capitalize.
  • Superclass – The name of the parent of the class is superclass and its child is a subclass, it should be preceded by the extends keyword. A class can only extend to one parent.
  • Interface Class – Interfaces are implemented by the class, they are separated by commas and are implemented by their keywords.
  • Body Class – The body of a java class is in the curly braces {}.

There are various types of classes in java like nested classes, lambda classes, and anonymous classes. Java Constructors are used to initializing any object in the class. The behavior of the class is defined by the methods.

Java Class and Object

2. Java Object

A program can have as many objects as it requires, objects in Java are real-life entities which interacts through methods. Classes are just a prototype but object physically exists, a Java object consists of-

  • State – A state represents the properties of an object and is defined by the attributes if the object.
  • Behavior – The behavior of an object represents the response of an object with other objects, it is defined by the method.
  • Identity – An identity enables one object to interact with another object, it gives a unique name to the Java object.

Take a break and learn how to create an object in Java with example?

Example of Java object is – Dog

Example of Java Object

3. Instantiating a Class in Java

Instantiating a class can also be called a declaration of an object in Java. When an object is created, it is known as instantiating of class. All the instances share common attributes and behavior of the class but the state for every object is different.

A class can have any number of objects or instances. For example

Java Class have number of objects

Here, the name of the class is a dog, the various objects are Dog 1, Dog 2, Dog 3 and Dog 4 who share the common attributes and behavior.

3.1 Initializing an Object in Java

Initializing is done by a java constructor, memory is allocated and a reference is given to that memory.

// Class Declaration
public class Dog
   {
// Instance Variables
      String name;
      String breed;
      int age;
      String color;
// Constructor Declaration of Class
         public Dog(String name, String breed,
         int age, String color)
            {
                this.name = name;
                this.breed = breed;
                this.age = age;
                this.color = color;
            }
// method 1
      public String getName()
    {
        return name;
     }
// method 2
      public String getBreed()
    {
        return breed;
    }
// method 3
      public int getAge()
    {
        return age;
    }
// method 4
      public String getColor()
       {
            return color;
       }
@Override
      public String toString()
       {
            return("Hi my name is "+ this.getName()+
            ".\nMy breed,age and color are " +
            this.getBreed()+"," + this.getAge()+
            ","+ this.getColor());
      }
public static void main(String[] args)
      {
            Dog tuffy = new Dog("shadow","german shephard", 2, "golden");
            System.out.println(tuffy.toString());
      }
 }

Output-

Screenshot of program

Have you heard about Java Copy Constructor?

3.2 How to Create an Object of a Class in Java?

There are basically 4 ways to create an object in Java, they are-

  • Using a new keyword

It is the most common method to create a Java object.

Example-

// creating object of class example
Example obj = new Example();
  • Using Class.forName(String className)

This method is a pre-defined class in java.lang with the name class.this method returns the Class object with string name associated with it.

Example-

Example obj = (Example)Class.forName("com.p1.Test").newInstance();
  • Using the Clone method in Java

This method returns the copy of the object.

Example-

// creating object of class Test
Example obj = new Example();
// creating clone of above object
Example obj1 = (Example)obj.clone();

Let’s Declare and Call Methods in Java with Practical Examples

  • Deserialization

Deserialization is just the reverse of serialization in which we use the byte stream to convert into the original state of a Java object.

Example-

FileInputStream file = new FileInputStream(filename);
ObjectInputStream in = new ObjectInputStream(file);
Object obj = in.readObject();

3.3 Creating multiple objects by one type only

  • We need different objects in different methods of a class, and saving different variables for them is not a good practice so we declare a static variable, this saves a lot of memory.

Example-

ClassName1 obj = new ClassName1(),
obj2 = new ClassName1();
  • A parent class reference can use to declare or store a subclass object, this helps in switching into different subclass objects using the same reference variable.

Example-

package JavaClassAndObject;
class DataFlair
{
	void courses()
	{
		System.out.println("Number of courses in DataFlair are 9");
	}
	void tutorials()
	{
		System.out.println("Number of tutorials in DataFlair are 35");
	}
}
public class DataFlairCourses
{
	public static void main(String args[])
	{
	DataFlair courseObject=new DataFlair(),tutorialsObject=new DataFlair();
	courseObject.courses();
	tutorialsObject.tutorials();
			
	}
}

Output-Screenshot

4. Anonymous Objects in Java

Anonymous objects are the Java objects that initiate but never store in reference variables. We use them for immediate calling and destroy them after use, i.e. method calling in java. Java objects widely use in many different libraries, for example in AWT libraries.

Example-

btn.setOnAction(new EventHandler()
    {
        public void handle(ActionEvent event)
            {
                System.out.println("Hello World!");
            }
    };

Here btn is the anonymous object to call EventHandler in java.

Summary

By the end of this article, we can see that classes and objects are the building blocks of a Java program. You should master these concepts no matter what programming language you master in.

Now, you know how to create and declare Java class and instantiate an object with the help of the above example.

Hope, you liked our explanation on Class and Object in Java. Share your experience through the comment section!

Next Article- Inheritance in Java

1 Response

  1. shravan says:

    i read the java documents ant it completed providing the java feature with example.

Leave a Reply

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

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.