×

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

flour pack problem in Java

Create a method called canPack and give it three int parameters: bigCount, smallCount, and objective. The bigCount option indicates the number of large flour bags (5 kilos each). The smallCount argument indicates...

3 minutes read.

Java 16

Java 16 is the most recent short-term incremental release, based on Java 15, and it was released on March 16, 2021. Records and sealed classes are just two of the...

11 minutes read.

Factorial of a Large Number in Java

We've already talked about a number's factorial. We must still go over the factorial of a large number separately, though. The method used to determine the factorial of a small...

8 minutes read.

Java Math.multiplyExact() method

In java, we are provided with multiplyExact method in the Math module. This Math module belongs to the java.lang package. In general, this method returns the product of the provided...

2 minutes read.

How to check the Java version in cmd

To make programs that can run on our systems, we need to install programming language-related software in our systems. Different programming languages require different types of software, aka IDEs (Integrated...

5 minutes read.

Java Keywords

Java Keywords The particular words which are used in java programming language that act like a key or important words to write a code are called java keywords. Java Keywords are...

4 minutes read.

How to Convert long to String in Java

How to Convert long to String in java It is used if we have to display a long number in the text field because everything is displayed as a String. A...

3 minutes read.

Multithreading in Java

Multithreading is a specialized form of multitasking. It is responsible for executing more than one task at a time of a single program, and each task is a separate thread. A program...

8 minutes read.

Highest precedence in Java

In Java, the operator is the first thing that springs to mind when discussing precedence. The order in which the operators in an expression are evaluated is controlled by a...

3 minutes read.

String Pool in Java

String Pool in Java: String is one of the most important discussed topics in Java. There are a lot of concepts related to the String and one of them is...

5 minutes read.

Java Math asin() Method

The asin() method of Math class computes the trigonometric Arc Sine (inverse of sine ) of an angle. The value returned is between -pi/2 to pi/2. Syntax: public static double asin(double a) Parameters: The...

1 minute read.

Java String startsWith() method

Java String startsWith() method checks whether current String starts with given prefix or not . Syntax: public boolean startsWith(String prefix) public boolean startsWith(String prefix, int offset) Parameters: prefix : It is sequence of character Returns: It returns...

2 minutes read.

Java Static Keyword

It can be either said that static declares the value to be the same, not only in the instance of a class but also as the whole. To declare a variable...

6 minutes read.

Convert JSON File to String in Java

Before understanding the conversion of JSON file to string, one must know about JSON. What is JSON? JSON stands for JavaScript Object Notation. It is an open standard format lightweight, text-based, and...

3 minutes read.

Comparator vs Comparable in Java

Comparator Vs Comparable in Java In Java, sorting of primitive data types can be done using different inbuilt functions that are available. But for sorting the collection of objects or types...

4 minutes read.

Java Stringjoiner Class

StringJoiner is a class which is used to construct a sequence of characters which are separated by a delimiter. Optionally, it starts with a provided prefix and ended with the...

5 minutes read.

Java Transient

Java Transient In Java, Serialization is used to convert an object into a stream of the byte. The byte stream consists of the data of the instance as well as the...

3 minutes read.

Count of Range Sum Problem in Java

In this article, we will discuss the basic approach or native approach used to count range sum problem in java. To solve this problem, we will check for numbers if they...

6 minutes read.

Java Switch string

A multi-way branch statement is the switch statement. It offers a simple method for allocating execution to various code sections according to the expression's value. Primitive data types, including bytes,...

3 minutes read.

Switch Case with Enum in Java

From some conditions, the java switch statement executes one statement. Similar to the If-Else-If ladder statement, this can be Byte, short, int, long, enum, string, and some wrapper types like...

4 minutes read.