Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What are Classes in Java?
2.1.
Example of Classes in Java
3.
Properties of Java Classes
4.
Declaring a Class in Java
5.
How to create a Class in Java?
6.
Components of Java Classes
7.
What are Objects in Java?
7.1.
Example of Objects in Java
8.
Characteristics of Java Object
9.
Declaring Objects in Java
10.
Initializing an Object in Java
11.
How to create an Object in Java?
11.1.
By new keyword
11.2.
By newInstance() method 
11.3.
By clone() method 
11.4.
By deserialization 
11.5.
By factory method 
12.
Anonymous Objects in Java
13.
Difference between Classes and Objects in Java
14.
Frequently Asked Questions
14.1.
What are classes and objects in Java?
14.2.
What are objects in Java? 
14.3.
What is a class in Java with an example?
15.
Conclusion
Last Updated: Mar 27, 2024
Easy

Classes and Objects in Java

Master Power BI using Netflix Data
Speaker
Ashwin Goyal
Product @
18 Jun, 2024 @ 01:30 PM

Introduction

Classes and Objects are the backbones of Java. A class specifies the shape and nature of an object. It is the logical concept upon which the entire Java language is based.

classes and objects in java

Classes serve as the foundation for Java object-oriented programming. A class must encapsulate any concept we want to apply in a Java program. In this blog, we’ll be learning all the basic concepts of Classes and Objects in Java. Let’s start with the classes in Java.

What are Classes in Java?

A Class is a blueprint that defines new data types. This blueprint or prototype can then be used to create objects.  It is not a real-world entity. Hence it has no physical existence. In simple words, classes do not occupy memory space. 

We declare the exact form and nature of a class when we define it. Classes denote the collection of properties or methods that is common to all the objects of that class. This is accomplished by specifying the data it holds as well as the code that manipulates that data. 

Example of Classes in Java

A class-named person is a blueprint for all the person that exists. All the people have some common features like name, age, etc. All these can be attributes of the object of this class.

class Person {
    // Class attributes
    String name;
    int age;

    // Class constructor
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
}
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Properties of Java Classes

The following are the properties of Java Classes:

  • Fields/Attributes: Java classes can have fields or attributes to store data. These represent characteristics or properties of objects created from the class.
     
  • Methods/Functions: Classes can contain methods that define behaviors or actions associated with objects. These methods can perform tasks and manipulate data.
     
  • Encapsulation: Java promotes encapsulation, which means bundling data (attributes) and methods together as a single unit (class). It hides the internal details and exposes only necessary functionalities.
     
  • Inheritance: Classes can inherit attributes and methods from other classes, allowing for code reuse and creating a hierarchy of related classes.
     
  • Constructor: Classes have constructors that initialize objects when they are created. Constructors ensure that objects start with a predefined state.

Declaring a Class in Java

The declaration of a class in Java includes the following components:

  • The keyword “class” is used in the class declaration. The first letter of the class name should be capitalized as per the convention.
     
  • Access Modifiers such as public, private, etc. are placed before the class name. Classes in java containing the main method should be declared as “public”.
     
  • The name of the superclass is followed by “extends” keywords (if any) for Inheritance.
     
  • Similarly, we must provide a comma-separated list of interfaces implemented by the class followed by “implements” keywords(if any).
     
  • Body of the class enclosed in curly braces{}.
     
  • Even if we don’t explicitly specify one, every Java class has at least one “constructor. While declaring classes, constructors are optional. A brief description of constructors is mentioned in the latter part of this article.
     

A simple declaration of Java class is given below:

access-modifiers class ClassName extends A implements B, C {
    // Attributes (instance variables)
    type instanceVariable1;
    type instanceVariable2;
    // ...

    // Constructors
    ClassName(parameter-list) {
        // Body of the constructor
    }

    // Methods
    type methodName1(parameter-list) {
        // Body of the method
    }

    type methodName2(parameter-list) {
        // Body of the method
    }
    // ...

    // Main method (optional)
    public static void main(String[] args) {
        // Body of the main method
    }
}

How to create a Class in Java?

Classes are the foundation for Java object-oriented programming. A class must encapsulate any concept we want to apply in a Java program. Classes in Java can contain a data member, method, constructor, nested class or interface. Let us look at how we can create a class.

Syntax

access_modifier class <class_name> {
    // Data members (variables)
    data member;

    // Methods
    method;

    // Constructors
    constructor;

    // Nested classes
    nested class;

    // Interfaces
    interface;
    
}


Explanation 

  • access_modifier represents the visibility of the class. It may be public, private or protected.
     
  • <class_name> goes by its name and defines the name of the class.
     
  • Data members are the variables or fields in the class.
     
  • Constructors are used to initialise the variables.
     
  • Destructors can also be used to destroy the class after its use to free up the memory.
     
  • A class may also contain another nested class which can also be called a class within a class.
     
  • The interface specifies a set of methods that a class has to follow.


Let us look at the example below to understand how to create classes in Java.

public class MyClass {
   // Field
   private int myField;
   // Method
   public void myMethod() {
       // Method body
       // Perform some actions
   }
}


In this example, we created a public class called Myclass. It contains a private integer variable named myField and a public void method named myMethod. In this way, we can add other variables that might be public or private, and we can also add other methods for a good functioning of a class in Java. We can also add constructors to initialise the variables and destructors to destroy the class after its use to free up the memory.

Components of Java Classes

There are many components of Java classes. Let us look at them one by one.

Modifiers: They represent the visibility of the class. It may be public, private or protected.

Class keyword: It is used to declare and create a class.

Class name: It is used to identify the class, and it should have a unique name to avoid any confusion.

Superclass: A class can also take the characteristics from another class called the superclass. 

Interfaces: The interface specifies a set of methods that a class has to follow.

What are Objects in Java?

A class is a blueprint for creating objects of type class. When we create an object of a class, we have created an instance of the class. Different objects have different names, behaviour and a state. The state of an object is stored in a variable, and this variable has a unique name to help identify the object. The behaviour of an object is defined by functions or methods. 

“A class can be visualized as a cookie cutter and objects as cookies. Unless we make cookies(Objects), there is no relevance to having a cookie-cutter(Class).”

Example of Objects in Java

Let’s start by looking at a simple example of a class. Here’s a class Rectangle that defines two instance variables: length and breadth. There are currently no methods in Rectangle.

class Rectangle { 
	double length; double breadth;
}

 

  • As mentioned earlier, a class defines a new type of data. In this case, the new data type is Rectangle.
     
  • It’s essential to keep in mind that declaring a class just creates a template. It does not create any physical entity(No memory allocation).
     
  • Objects of type Rectangle are created as a result of the above code and these objects occupy memory.
     
  • To create an object of a class having physical existence, we have to write a statement like this:
     
Rectangle rec = new Rectangle(); // creates a Rectangle object called rec


All objects of the same class share a resemblance by having the same behaviour.

Characteristics of Java Object

To learn and use Java, we have to identify three key characteristics of objects:

  • The behaviour of the object – what can be done with the object?
     
  • The state of an Object – how will the object react when something is done?
     
  • The identity of an object – how will the object be distinguished from others?

Declaring Objects in Java

In Java, we can declare objects by following the syntax:

ClassName objectName;


For declaring an object in Java, We must define the class name in which the object is present, followed by its name, which helps us identify the object in a class.

Let us look at an example of a class car which contains a car Mycar.

public class Car {
   // Class definition
   Car myCar;
 // Object Mycar
}

Initializing an Object in Java

In Java, you can initialize an object by following these steps:

  • Create a Class: First, you need to create a class that defines the structure and behaviour of the object. This class serves as a blueprint for creating objects.
     
  • Define Fields: Inside the class, define fields (also called attributes or instance variables) to represent the object's properties or characteristics. These fields should specify the data that each object will store.
     
  • Create a Constructor: Implement a constructor method within the class to initialize the object. The constructor is called when you create a new instance of the class. It assigns initial values to the object's fields.
     
  • Create an Object: To initialize an object, create an instance of the class using the new keyword and the constructor you defined. Pass any required initial values to the constructor.

How to create an Object in Java?

There are different ways of creating an object. Let us look at them one by one.

By new keyword

It is the most common method to create an object in the class. We can create an object using new keyword.

ClassName objectName = new ClassName();

By newInstance() method 

We can also use the newInstance() method in Java to create an object in a class. The newInstance() method is a reflective way to create an object in Java.

ClassName objectName = ClassName.class.newInstance();

By clone() method 

The clone() method is used in Java to create a copy of a pre-existing object.

ClassName objectName = existingObject.clone();

By deserialization 

We can also create an object from a serialised file in Java by using the deserialisation method.

ObjectInputStream in = new ObjectInputStream(new FileInputStream("object.ser"));
ClassName objectName = (ClassName) in.readObject();

By factory method 

The factory method is used to create and return an object of a class.

public class ClassName {
   // Private constructor
   private ClassName() {
   }
   
   // Factory method
   public static ClassName createObject() {
       return new ClassName();
   }
}
// Usage
ClassName objectName = ClassName.createObject();

Anonymous Objects in Java

Anonymous objects in Java are like tools you use once and throw away. We don't give them a name or a place to stay. They're handy for quick tasks. For example, imagine you have a calculator. You can borrow it for one calculation and return it immediately without keeping it around. That's how anonymous objects work – you create them, use them for a specific job, and forget about them.

Anonymous objects are objects created on the fly, often for a specific and immediate purpose. They are not assigned to a reference variable and are not given a name. These objects can be used to call methods directly or to pass as arguments to other methods.

Difference between Classes and Objects in Java

Basis Classes Objects
Definition Classes are used as a blueprint for creating objects. Instances are created from classes.
Purpose The purpose of classes is to define the structure and behaviour. It is used to represent specific instances.
Example Class ‘person’ represents the properties of a person.  Object ‘Ram’ of a class person represents an instance of a person.
Reusability It is used to create multiple objects. It represents a single instance.
Static Members Classes can have static members and methods. Objects does not have any static members.

Frequently Asked Questions

What are classes and objects in Java?

A class in Java is a blueprint from which objects are made. Objects are instances of type class.

What are objects in Java? 

They are the members present in a Java class, also called instances a class. Different objects have different names, behaviour and a state.

What is a class in Java with an example?

In Java, a class is a blueprint for creating objects. It defines the structure and behaviour of those objects. For example, a Car class can specify the attributes (colour, speed) and methods (start, stop) that cars should have.

Conclusion

Classes and Objects are the basic building blocks of object-oriented programming languages like Java, C++, etc.  In this article, we have learned the Syntax, examples, and components of both classes and objects. We have also discussed multiple ways to create an object of a class. Hope you have learned something new today.

Previous article
What is an Object in OOPS(Object Oriented Programming)
Next article
Anonymous Class In Java
Live masterclass