Javatpoint Logo
Javatpoint Logo

Class Definition in Java

In object-oriented programming, a class is a basic building block. It can be defined as template that describes the data and behaviour associated with the class instantiation. Instantiating is a class is to create an object (variable) of that class that can be used to access the member variables and methods of the class.

A class can also be called a logical template to create the objects that share common properties and methods.

For example, an Employee class may contain all the employee details in the form of variables and methods. If the class is instantiated i.e. if an object of the class is created (say e1), we can access all the methods or properties of the class.

Defining a Class in Java

Java provides a reserved keyword class to define a class. The keyword must be followed by the class name. Inside the class, we declare methods and variables.

In general, class declaration includes the following in the order as it appears:

  1. Modifiers: A class can be public or has default access.
  2. class keyword: The class keyword is used to create a class.
  3. Class name: The name must begin with an initial letter (capitalized by convention).
  4. Superclass (if any): The name of the class's parent (superclass), if any, preceded by the keyword extends. A class can only extend (subclass) one parent.
  5. Interfaces (if any): A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements. A class can implement more than one interface.
  6. Body: The class body surrounded by braces, { }.


Java Class Example

Example 1:

Let's consider the following example to understand how to define a class in Java and implement it with the object of class.


Class Definition in Java

Example 2:

In the following example, we are creating two classes Employee and EmployeeClass. The Employee class fetches and displays the employee details. In the EmployeeClass, we create the objects of Employee class and use its methods. Here, we are initializing the objects using the class constructor.


Class Definition in Java

Youtube For Videos Join Our Youtube Channel: Join Now


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Trending Technologies

B.Tech / MCA