×

Java Class Syntax

A class is a fundamental building piece in object-oriented programming. It can be characterised as a template that outlines the information and actions connected to the creation of a class. A class can be instantiated to produce an object (variable) that can be used to access its member variables and methods.

A class may also be used as a conceptual template to build objects with shared attributes and operations.

For instance, all the information about an employee may be presented in the form as properties & methods in the Employee class. We can access all of the class's methods or properties if indeed the class is instantiated, or if an object (let's say e1) of the class is formed.

Defining a Class in Java

Java offers the reserved keyword class for class definitions. The class name must come after the keyword. We declare variables and methods inside the class.

The following elements are often included in class declarations in the following order:

  • Modifiers: A class may have default access or be made public.
  • class keyword: A class is created with the class keyword.
  • Name of the class: The name must start with a letters(capitalized by convention).
  • Superclass (if any): If there is one, the term extends is followed by the name of the superclass. Only one parent can be extended (subclassed) by a class.
  • (If any) interfaces a list of the interfaces that the class, if any, implements, separated by commas, should be included. A class may support several interfaces.
  • Body: A brace-encircled image of the class.

Syntax:

<access specifier> class Name  
{  
// variables in the class
// methods in the class
}  

Example 1 of a Java Class Let's look at the example below to see how to create a subclass in Java and use an object of the class to implement it.

Maths.java

// Imporating all the requried packages
import java.io.*;


// defining a class Maths 
public class Maths {  
     
   // Defining the variabled x and y 
   int x;  
   int y;  
  
   // Initializing the class variables 
   public Maths (int x, int y) {  
      this.x = x;  
      this.y = y;  
   }  
  
   // This method performs the addition operation
   public int addnum () {  
      int ans = x + y;  
      return ans;  
   }  
  
   // This method performs the subtraction operation
   public int sub () {  
      int ans = x - y;  
      return ans;  
   }  
  
   // This method performs the multiplication operation  
   public int mult () {  
      int ans = x * y;  
      return ans;  
   }  
  
   // This method performs the division operation  
   public int div () {  
      int ans = x / y;  
      return ans;  
   }  
  
  
   // main method starts here  
   public static void main(String[] args) {  
      // object creation for the maths class
      Maths obj = new Maths(10, 30);  
        
      // calling the methods of Maths class  
      System.out.println("Addition of two numbers is :" + obj.addnum());  
      System.out.println("Subtraction of two numbers is :" + obj.sub());  
      System.out.println("Multiplication of two numbers is :" + obj.mult());  
      System.out.println("Division of two numbers is :" + obj.div());  
  
   }
   }  

Output:

Addition of two numbers is : 40
Subtraction of two numbers is : -20
Multiplication of two numbers is : 300
Division of two numbers is : 3

Example 2:

The classes Employee & EmployeeClass are being created in the example below. The employee details are retrieved and shown by the employee class. We construct objects of the Employee class in the EmployeeClass using its methods. Here, we're utilising the class function Object () { [native code] } to initialise the objects.

Emp.java

// defining a class emp
class Emp {  
    // declaring variables  
    int eid;  
    String n;  
    String bran;  
    float income;  
  
    // Initializing the class variables 
    void intial (int id, String n, String d, float sal) {  
        this.eid = id;  
        this.n = n;  
        this.bran = d;  
        this.income = sal;  
    }  
  
    // Displaying employe details using show method  
    void show() {  
        System.out.println("Employe id is : " + eid );  
        System.out.println("Employe name is " + n );  
        System.out.println("Employe department is : " + bran );  
        System.out.println("Employe income is : " + income );  
    }  
}  
  
public class EmployeeClass {  
    // main method starts here  
    public static void main(String[] args) {  
        // object creation for the Emp class 
    Emp o1 = new Emp();    


  
    // calling the methods of Emp class    
    o1.intial (1, "Manoj", "Software", 95000);    
      
    o1.show();    
    }  
}  

Output:

Employe id is : 1
Employe name is Manoj
Employe department is : Software
Employe income is : 95000

Related Topics

What is the ambiguity problem in Java?

The ambiguity problem in Java occurs when a method or constructor is overloaded with two or more methods with the same name but different parameters. This can confuse when multiple...

6 minutes read.

Iterate JSON array in Java

This article is going to equip the knowledge about what JSON array is and how it works and also how is it distinct with the generic array. Json Array Ordered lists of...

4 minutes read.

Java Char Keyword

The java char keyword is a data type which is defined as character data type.Char keyword belongs to a primitive data type where the data types are classified into primitive...

4 minutes read.

Java File Extension

A computer file's suffix is called its file extension. It is easily recognized since it appears immediately after a period (.) in the file name. Consider the file Demo.java as an...

3 minutes read.

Java 9 Tutorial

The Java 9 is most popular release of java programming to make it platform modular. It is used to improve JDK and java implementation security. It provides JAVA SE and...

3 minutes read.

Sleep Time in Java

Sleep is amethod in java that is related to thread class and it is a concept of multithreading and is used to stop the execution of the current thread a...

4 minutes read.

Best Practices to use String Class in Java

Use String Builder or String Buffer for String concatenation in place of + operator.Compare two strings by equals( ) method instead == operator.Call .equals( ) method on a known String...

3 minutes read.

Missing Number in an Arithmetic Progression in Java

Given an array that shows the elements of an orderly arithmetic progression. Find the missing number to complete the succession of elements. Example:  Input: a [ ] = {2 , 4 , 6...

3 minutes read.

Converting Roman to Integer Numerals in java

In this article, you will be acknowledged about the process of conversion of roman numbers to integers in java. The most important approaches are discussed and also the implementation of...

3 minutes read.

Java Try-Catch Block

Java Try Block The handling of the exceptions in a block of code is done with the help of java try block. It throws the code that is enclosed in a...

3 minutes read.

Minimum Window Subsequence in Java

In this article, you will be very well acknowledged about the minimum window subsequence, what is the approach and how it is implemented. The example program is also executed and...

4 minutes read.

Getting Synchronized Set from Java HashSet

The synchronizedSet() technique for java.util.Collections class is utilized to return a synchronized (string safe) set supported by the predetermined set. To ensure sequential access, it is important that everything admittance...

4 minutes read.

Moran Numbers in Java

In this article, we will be acknowledged about the moran numbers in Java, how they are formed, what are the approaches to achieve the moran numbers. Moran Number A moran numbers are...

3 minutes read.

How to Convert int to double in Java

How to Convert int to double in Java When two variables of different types are involved in the single expression, Java compiler uses built-in library function to convert the variable to...

2 minutes read.

Arithmetic Operations on String in Java

Introduction Arithmetic, Relational, Bitwise, and Logical operators are all available in Java. Simple mathematical calculations are performed using Java arithmetic operators. Basic Arithmetic operators are considered in Java to be Addition,...

4 minutes read.

Union in Java

Sets.union() method in Java returns an immutable representation of both the union of two sets. Every element that is present in either backup set is included in the set that...

2 minutes read.

Graphics Program in Java

Graphics Program in Java The graphics program in Java is part of the Swing program in Java. In this section, we will learn about the implementation of custom graphics using some...

6 minutes read.

Java finally

Java finally: There are some statements in a program whose execution is extremely important. For example, closing of a database connection. Statements that do the closing of the database connection...

5 minutes read.

Local Minima in Java

An Array Finding a local minimum in an array a[0. m-1] of different integers is the job. A[i] is considered a local minimum if it is smaller than two of its...

4 minutes read.

Java Math nextDown() Method

The nextDown() method of Math class returns the floating-point number adjacent to the argument in direction of the negative infinity. Syntax: public static double nextDown (double d)public static float nextDown (float f) Parameters: The...

2 minutes read.