DEV Community

Cover image for Classes and Objects in Java
Karthick (k)
Karthick (k)

Posted on

Classes and Objects in Java

In Java, classes and objects form the foundation of Object-Oriented Programming (OOP). They help model real-world entities and organise code in a structured way.

A class is a blueprint used to create objects that share common properties and behaviour.
An object is an instance of a class. It represents a specific entity created from the class template.

Classes

A class in Java defines a new data type that can include fields (variables) and methods to define the behaviour of the objects created from the class.

class ClassName {
    // Fields
    dataType fieldName;

    // Constructor
    ClassName(parameters) {
        //Initialise fields
    }

    // Methods
    returnType methodName(parameters) {
        // Method body
    }
}
Enter fullscreen mode Exit fullscreen mode
  • ClassName: The name of the class.
  • fieldName: Variables that hold the state of the class.
  • Constructor: A special method used to initialise objects.
  • methodName: Functions defined within the class to perform actions.

Objects

An object is an instance of a class. It is created using the new keyword followed by the class constructor.

Syntax

ClassName objectName = new ClassName(arguments);
Enter fullscreen mode Exit fullscreen mode

Difference between Local Variable and Global variables:

*Quick Comparison Table: What is static and non-static in Java *

Top comments (0)