What is class in Java

A class in Java is a blueprint or template that defines the data and behavior of objects. It's a fundamental building block of object-oriented programming (OOP), and is used to model real-world entities as objects in your code.

A class consists of:

  1. 1. Variables: These are also known as fields or instance variables. They represent the state of the object and store the data associated with the object. The variables are declared within the class, but outside of any method.

  2. 2. Methods: These are the actions that can be performed on the object. They define the behavior of the object and can access and manipulate the variables of the object. Methods are declared within the class, just like variables.

  3. 3. Constructors: A constructor is a special type of method that is used to initialize the object when it's created. The constructor has the same name as the class and is called when an object of the class is created.

  4. 4. Blocks: A block of code in Java is a set of statements that can be grouped together. There are two types of blocks in Java: instance initializer blocks and static initializer blocks. Instance initializer blocks are executed whenever an object of the class is created, while static initializer blocks are executed once when the class is first loaded into memory.

  5. 5. Nested classes: A class can contain another class within it, which is known as a nested class. There are several types of nested classes in Java, including inner classes, static nested classes, and anonymous inner classes.

Here's a simple example of a class in Java:

public class Student { // Variables String name; int age; // Constructor public Student(String name, int age) { this.name = name; this.age = age; } // Method public void printDetails() { System.out.println("Name: " + name); System.out.println("Age: " + age); } }

In this example, the Student class has two variables: name and age. The constructor Student(String name, int age) is used to initialize the object when it's created, and the printDetails() method is used to display the details of the student.

To create an object of the class, you would use the following code:

Student student = new Student("John Doe", 22); student.printDetails();

This would create a new object of the Student class and initialize it with the name "John Doe" and age 22. The printDetails() method would then be called on the object to display the details.