Class and Object in Java

Classes

Class is a user-defined data type that defines its properties and functions. Classes are a blueprint for creating an object. For example, Human Being is a class, body parts of the human are properties, and actions performed by body parts are known as methods. With the help of the class, we can create as many objects as we want. The class contains properties, constructors, methods, getters, setters, etc.

Info

Note: We need to define the class first to define an object.

Declaring A class

In Java, a class can be defined using the class keyword followed by the class name; and the class body enclosed by a pair of curly braces {}.

Syntax

class ClassName  {
// properties
// methods
} 

In the above syntax:

  • The class is the keyword used to initialize the class.
  • ClassName is the name of the class.
  • Body of the class consists of properties, constructors, getter and setter methods, etc.
  • Properties are used to store data.
  • Methods are used to perform some operations.

Example To Declare Class

class Computer{
// properties
int id;
String name;
double price;
// methods

void printDetails(){
  System.out.println("ID is "+this.id);
  System.out.println("Name is "+this.name);
  System.out.println("Price is "+this.price);
  }
}
Info

Note: Here, this keyword refers to the current object in a method.

Declaring A Objects

Objects are the class instance and are declared by using a new keyword followed by the class name.

Syntax

var objName = new ClassName();

In the above syntax:

  • The new is the keyword used to declare the instance of the class.
  • The objName is the name of the object.
  • ClassName is the name of the class whose instance variable has been created.

Example Of Class And Object

class Computer{
// properties
int id;
String name;
double price;
// methods

void printDetails(){
  System.out.println("ID is "+this.id);
  System.out.println("Name is "+this.name);
  System.out.println("Price is "+this.price);
}

}
// Main class
public class Main {
  // main method
  public static void main(String[] args) {
     //Creating a object from class Computer
    Computer com1 = new Computer();
    // Assign value to class properties
    com1.id = 1;
    com1.name = "MSI";
    com1.price = 233.0;
    System.out.println(com1.id);
    System.out.println(com1.name);
    System.out.println(com1.price);
  }
}
Show Output

this keyword in Java refers to the current instance of the class.

Info

Note: You can also create a class in a different file. It makes your code more readable.