What is Class in Java (with Examples)

We know that Java is a pure object-oriented programming language that allows us to develop a program by using the concept of class and object. A class encapsulates the basic structure of a Java program in a single unit.

A class in Java is a template or a blueprint that can be used to create objects of the same type. It is a fundamental building block of a pure object-oriented programming language like Java.

A class represents a group of objects that share common properties (attributes) and behavior (methods). For example, if “computer” is a class, supercomputer, mainframe computer, minicomputer, desktop, and laptop are objects.

The objects like supercomputer, mainframe computer, minicomputer, desktop, and laptop are specific instances of the Computer class. Each object can have the specific properties such as speed, storage, portability and behavior like processing. Loot at the below figure.

Realtime example of class in Java.

You can see in the above real-time example, the properties of different computer (i.e. objects) are different and the behavior of the supercomputer is parallel processing whereas, the desktop and laptop have the serial processing.

Let’s take another real world example to understand a class in Java. Suppose “Square” is a class and square1 and square2 are the instances of class “Square”. The length of each side of the square (in cm) defines the unique characteristic of each object. Its behaviors is area and perimeter.

Thus, we can say that a class in Java represents a real-world entity by encapsulating its properties (attributes) and methods (behaviors). For example, properties are sides of a square, speed, storage, and portability of a computer. Behaviors are calculating area and perimeter for a square, and processing of a computer.

Syntax to Define Class in Java

You can define a class by using a keyword “class”. The general syntax to define a class in Java program is as follows:

access_modifier class ClassName {
 // Fields (attributes)
    DataType fieldName1;
    DataType fieldName2;

 // Constructor(s)
    ClassName(parameters) {
        // Initialize fields
    }
 // Methods (functions)
    ReturnType methodName(parameters) {
        // Method body
    }
}

This is the basic syntax to define a class. In Java, a class is a code container that groups all the program code. The definition of the class begins with an access modifier, which specifies which classes have access to it.

Next, the keyword class and the name of class come. Every class must be enclosed within the curly braces ({ }). Inside the class, fields, constructors, and methods are the components of a class. However, there may be also other components inside a class besides to them.

Example of Class in Java

Let’s take an example of a Java program to illustrate the above syntax of a class.

Example 1:

// Define the Computer class.
class Computer {
 // Common properties
    String type; // data type string.
    int memory; // data type int.
    double speed; // data type double.

 // Constructor to initialize the common properties of computer.
    Computer(String type, int memory, double speed) {
        this.type = type;
        this.memory = memory;
        this.speed = speed;
    }

 // Method to display computer details.
    void displayDetails() {
        System.out.println("Type: " + type);
        System.out.println("Memory: " + memory + "GB");
        System.out.println("Speed: " + speed + "GHz");
    }
}

// Main class
public class Main {
public static void main(String[] args) {
 // Create objects of the Computer class and pass argument values to its constructor.
    Computer supercomputer = new Computer("Supercomputer", 1024, 10.0);
    Computer desktop = new Computer("Desktop", 16, 3.5);
    Computer laptop = new Computer("Laptop", 8, 2.8);

 // Display details of each computer.
    supercomputer.displayDetails();
    System.out.println();
    desktop.displayDetails();
    System.out.println();
    laptop.displayDetails();
  }
}

When you will execute the above example program, the following output will produce on the console.

Type: Supercomputer
Memory: 1024GB
Speed: 10.0GHz

Type: Desktop
Memory: 16GB
Speed: 3.5GHz

Type: Laptop
Memory: 8GB
Speed: 2.8GHz

Components of Computer Class

Let’s break down the components of the Computer class used in the earlier example, explaining each part of the code.

1. Access Modifiers for a Class in Java:

The definition of the class starts with an access modifier (default in this case), which allows to access in the same package. The applicable access modifier for a class in Java is as follows:

  • public Access Modifier: If a class is declared as public, you can access it from anywhere in the program. This means it is accessible from the same package or from other packages (when imported).
  • Default Access Modifier: If no access modifier is specified with a class, the class is considered having default access (also called package-private access). A class with default access is only accessible within the same package. You cannot access it from classes in other packages.

2. Class Declaration:

class Computer {

Next, the keyword class defines the blueprint for creating objects. After that, the name of the class “Computer” comes. Every class definition starts with opening a curly brace ({) and ends with a closing curly brace (}).

3. Properties (Attributes)

Then, we have defined fields or attributes that hold the data about the object. In other words, we have defined instance variables such as type, speed, storage, and isPortable whose data types are string, double, int, and boolean, respectively. The fields represent the state or attributes of objects created from the class.

String type;
double speed; 
int storage;
boolean isPortable;

4. Constructor

Next, we have defined a constructor in the Java program, which is a special type of method used to initialize objects of the class. We have defined four parameters inside the parentheses of the constructor to set the initial values of the object’s properties. Then, we have used “this” keyword to distinguish between instance variables and parameters.

Computer(String type, double speed, int storage, boolean isPortable) {
    this.type = type;
    this.speed = speed;
    this.storage = storage;
    this.isPortable = isPortable;
}

5. Methods (Behaviors)

Next, we have declared an instance method named displayDetails() to display the properties of an object. We have used System.out.println to print the details to the console.

void displayDetails() {
    System.out.println("Type: " + type);
    System.out.println("Speed: " + speed + " GHz");
    System.out.println("Storage: " + storage + " GB");
    System.out.println("Portable: " + (isPortable ? "Yes" : "No"));
}

6. Main Class

After that, we have defined another class named Main with a public access modifier. Inside the Main class, we have declared main method (public static void main(String[] args)) which is an entry point to start the execution of any Java program. The main method starts with an opening curly brace and ends with a closing curly brace.

public class Main {
    public static void main(String[] args) {

The main method is a special method which is an entry point of program execution. In other words, when the class Computer is run by the Java Runtime Environment, it will start to execute the Java code from the main method. Note that not every Java class should have a main method.

7. Creating Objects (Instances)

Inside the Main class, we have created three objects of Computer class and passed argument values of types string, double, and int to its constructor.

Computer supercomputer = new Computer("Supercomputer", 1024, 10.0);
Computer desktop = new Computer("Desktop", 16, 3.5);
Computer laptop = new Computer("Laptop", 8, 2.8);

8. Calling Methods

Next, we have called instance methods using object reference variables one by one. Note that a method will execute when you will call it. Otherwise, it will not execute by JVM.

supercomputer.displayDetails();
desktop.displayDetails();
laptop.displayDetails();

Example 2:

class Student {
// Declaration of instance variables or fields.
   String name;
   int rollNumber;
   double marks;

// Declare a constructor.
   Student(String name, int rollNumber, double marks) {
       this.name = name;
       this.rollNumber = rollNumber;
       this.marks = marks;
   }

// Declare an instance method to display student details.
   void displayDetails() {
      System.out.println("Name: " + name);
      System.out.println("Roll Number: " + rollNumber);
      System.out.println("Marks: " + marks);
   }
}
public class Main {
public static void main(String[] args) {
 // Creating a Student object.
    Student student1 = new Student("John Doe", 101, 95.5);

 // Calling method to display details
    student1.displayDetails();
  }
}

Rules for Creating a Class in Java

In order to define or create a class in Java program, you should follow some rules below:

  • The class keyword is mandatory to define a class in Java.
  • By convention, the name of a class in Java should start with an uppercase letter and use camel case for readability. For example, Student, School, rollNo, MyClass, etc. It is not recommended to use lowercase letter to define a class. For example, myclass is invalid class name in Java.
  • You can declare multiple classes in a Java file, but only one can be public. The name of the file must match the name of the public class (if present), followed by the .java extension. For example:
// File: MyClass.java
public class MyClass {
    // Public class
}

class HelperClass {
    // Non-public class
}

Incorrect:

// File: MyClass.java
public class AnotherClass { // Error: File name must match public class name
    // Public class
}
  • Java supports single inheritance only. Therefore, a class can inherit from only one other class using the extends keyword. For example:
class ParentClass {
    // Parent class code
}

class ChildClass extends ParentClass {
    // Child class code
}

Incorrect:

class Parent1 {
    // Parent 1
}

class Parent2 {
    // Parent 2
}

class ChildClass extends Parent1, Parent2 { // Error: Java does not support multiple inheritance
    // Child class
}
  • Java restricts multiple inheritance to prevent ambiguity caused by the diamond problem. However, multiple inheritance can be achieved using interfaces.

Types of Classes in Java

There are two types of classes in Java that are as:

  • Built-in classes
  • User-defined classes

1. Built-in Classes:

  • Built-in classes are the predefined classes provided by Java and are available in the Java Development Kit (JDK).
  • They are part of Java’s standard library which can be used directly in programs without the need for the user to define them.
  • These classes cover a wide range of functionality, including data structures, file handling, date and time manipulation, and more.
  • Examples of Built-in Classes:
    • java.util.Date: Used for working with dates.
    • java.util.LinkedList: A data structure that represents a doubly-linked list.

Example 3:

import java.util.Date;
import java.util.LinkedList;

public class BuiltInClassExample {
public static void main(String[] args) {
 // Using java.util.Date
    Date today = new Date();
    System.out.println("Current Date: " + today);

 // Using java.util.LinkedList
    LinkedList<String> names = new LinkedList<>();
    names.add("Alice");
    names.add("Bob");
    System.out.println("Names: " + names);
  }
}
Output:
    Current Date: Mon Dec 09 10:30:00 IST 2024
    Names: [Alice, Bob]

2. User-defined Classes:

User-defined classes are those classes which are created by users or programmers to add custom functionality and define their own logic or structure. A user-defined class can encapsulate data (properties) and behaviors (methods) to represent a real-world entity.

Example 4:

// User-defined class
class Person {
   String name;
   int age;
   
   Person(String name, int age) {
        this.name = name;
        this.age = age;
   }
   void displayDetails() {
     System.out.println("Name: " + name + ", Age: " + age);
   }
}
public class UserDefinedClassExample {
public static void main(String[] args) {
// Creating objects of the user-defined class
   Person person1 = new Person("Alice", 25);
   Person person2 = new Person("Bob", 30);

// Displaying details
   person1.displayDetails();
   person2.displayDetails();
  }
}
Output:
    Name: Alice, Age: 25
    Name: Bob, Age: 30

Differences Between Built-in and User-defined Classes

AspectBuilt-in ClassesUser-defined Classes
DefinitionPredefined in the Java Development Kit (JDK).Created by the user or programmer to define custom classes.
AvailabilityReady to use in the Java program by importing relevant packages.Defined explicitly by the user in their code.
Examplesjava.util.Date, java.util.LinkedList, java.io.File.Person, Car, BankAccount (defined by user).
CustomizationLimited to available methods and functionality.Fully customizable based on user or programmer.

Please Share Your Love.

Leave a Reply

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