Class in Java

A Class is a blueprint or template from which objects are created. A Class is a group of objects which have common properties.

In Java everything is encapsulated under classes. Class is the core of Java language. Class can be defined as a template/ blueprint that describe the behaviors /states of a particular entity.

In other words, Class is a blueprint or a set of instruction to build a specific type of object.

Syntax to declare a class

class class_name { 




Key points about Class

  • A Class is declared using class keyword.
  • Class is also known as a user defined datatype.
  • The data or variables defined within a class are called instance variables and the code that operates on this data is known as methods.
  • A Class can have only public or default (no modifier) access specifier.
  • It can be either abstract, final or concrete (normal class).
  • It may optionally extend one parent class. By default, it will extend java.lang.Object package.
  • The class's variables and methods are declared within a set of curly braces {}.

Component of a Class in Java

  • Modifiers : A Class can be public or has default access.
  • Class name: Class name should begin with initial letter.
  • Fields: A Class can have fields of different-different data types.
  • Methods: A method in Class is like a function which is used to expose the behavior of an object
  • Constructors: A constructor is similar to a method (but not actually a method) that is invoked automatically when an object is instantiated. Read more Constructor
  • Blocks: A Class can contains Static blocks.
  • Nested class and interface: A Class can have nested class also and a Class can implements interface.

Variable types in Class

A class can contain any of the following variable types.

  • Local variables
  • Instance variables
  • Class variables

Read more Java Variables

Method in Java Class

In Java Class, a method is like a function which is used to expose the behavior of an object.

Read more Java methods

Class example in Java

Suppose Employee is a Class and Employee Class have employee name, age and salary. Let see Class syntax in Java.

class Employee {

       String employeeName;

        int employeeAge;

        int employeeSalary;


Design principle of a Class

While creating a class, a class must follow the following SOLID principles.

  • Single Responsibility Principle (SRP)- A class should have only one reason to change
  • Open Closed Responsibility (OCP)- It should be able to extend any classes without modifying it
  • Liskov Substitution Responsibility (LSR)- Derived classes must be substitutable for their base classes
  • Dependency Inversion Principle (DIP)- Depend on abstraction and not on concretions
  • Interface Segregation Principle (ISP)- Prepare fine grained interfaces that are client specific.