Class in Java::

Published: (February 7, 2026 at 12:49 AM EST)
2 min read
Source: Dev.to

Source: Dev.to

Class

Definition

A class is a blueprint or template used to create objects. It defines the properties (variables) and behaviors (methods) that the objects created from it will have.

Declaration

A class must be declared using the class keyword.

class MyClass {
}

Naming Rules

  • The class name must start with a letter (A–Z or a–z).
  • It cannot start with a digit.
  • It must not contain spaces.
  • Only the characters _ and $ are allowed as special characters.
  • Java reserved keywords cannot be used as class names.
  • By convention, the class name should start with a capital letter, and if it contains multiple words, each word should start with a capital letter.
class StudentDetails

Body and Structure

The body of a class must be enclosed within curly braces {}.

class Car {
    // fields and methods
}

File Naming

  • A .java file can contain only one public class.
  • If a class is declared as public, the file name must match the public class name.
public class Student {
}

Access Modifiers

  • A class can have an access modifier such as public, or no modifier (default package‑private).
  • Top‑level classes cannot be private or protected.

Main Method

To execute a Java program, the class must contain the main() method.

public static void main(String[] args) {
    // program entry point
}

Multiple Classes in One File

Multiple classes can be defined in a single file, but only one of them may be declared public.

0 views
Back to Blog

Related posts

Read more »

Constructor in java

What is Constructors? A constructor is a special method in Java that is automatically executed when an object of a class is created. It is mainly used to initi...

Java_Local&Global_Variable

Local Variable - Declared inside a method, constructor, or block {}. - Accessible only within that method or block. - Must be initialized before use. - Lifetim...

Constructor

What is a Constructor? A constructor is a special block in a class that runs automatically when an object is created. Its job is to set initial values for the...