×

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

Fork Join in Java

Multithreaded processors are being introduced in new computer systems today. The operation is faster due to multicore CPUs. Therefore, it becomes essential for a programmer to leverage multithreaded processors effectively...

4 minutes read.

Check if the given array is mirror inverse in Java

The primary objective is to check whether the given array is mirror inverse or not. The values and position of the specified array are switched, and a duplicate array is created....

3 minutes read.

Java Program to Add Digits Until the Number Becomes a Single Digit Number

We will develop Java programme that increase a number's digit count in order to reduce it to one. The issue is also known as the digit root problem. Example Consider the case where...

3 minutes read.

Java Math sin() Method

The sin() method of Java Math class returns the trigonometric sine of the specified angle. Syntax: public static double sin(double a) Parameters: The parameter ‘a’ represents an angle measured in radians. Return Value: The sin() method...

1 minute read.

Java Strings

String class is the most used class in Java programming language. The string is the sequence of characters, which is treated as objects in Java. Creating String objects We create String objects...

5 minutes read.

How to calculate time difference in Java

In this tutorial, we learned about how to calculate time differences in java language and which methods use to find the difference and its example. Prerequisite To understand this example, you need...

5 minutes read.

Java String split() method

Java String split() method split current String against given regular expression and returns a char array. Syntax: public String split(String regex)                 public String split(String regex, int...

2 minutes read.

Polygonal Number in Java

What does a Java Polygonal Number Mean? In mathematics, a polygonal number refers to a number that is expressed through dots or pebbles arranged in a regular polygonal pattern. Alphas are...

4 minutes read.

Chromatic Number in Java

The chromatic number is the bare minimum of colours necessary to accurately colour any graph. To put it another way, the chromatic number can be thought of as the bare...

6 minutes read.

Misc Operators in Java

In this article, we are going to learn about the misc operators in Java. Misc operators are nothing but the miscellaneous operators. The java programming language supports some of the...

4 minutes read.

Byte to Hex in Java

Java exclusively uses byte data types to store in a byte array, which is an array. Each component of a byte array has a default value of 0. Hex String -...

3 minutes read.

Java Buffered Writer

BufferWriter Class: It is used to write the data more efficiently. This class is present in the java.io package, it inherits the data from the Writer class. Writer class is...

4 minutes read.

Character Array in Java

A character array is an array which holds values of character data types. It is different from a string array. The character array, string, and StringBuffer classes in the Java...

4 minutes read.

Difference between next() and nextline() in Java

One of the simplest methods for receiving input of the basic data types, also including int, double, and strings, in Java, is to use the Scanner class, which is part...

3 minutes read.

Java Math round() Method

The round() method of Java Math class returns a long or an int value that is closest to the argument and is rounded to positive infinity. Syntax: public static int round(float a)public...

2 minutes read.

Annotations in Java

Annotations in Java Java Annotations are metadata about the source code. They do not have any direct effect on the execution of the java program. Annotations in Java were introduced in...

4 minutes read.

Java IO

It is a part of java libraries but is often known as I/O streams, file I/O, and file handling. The Java I/O concept satisfies the need for input processing and...

4 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.

Java Numbers

We use primitive data types like byte, int, long, double, etc to work with the numbers, When we need objects, we use wrapper class like Integer, Double, Long, Byte, etc....

2 minutes read.

How to get the current date and time in Java

Introduction: In this article, we are going to discover many processes for Getting the existing-day Date and Time in Java. Most programs require timestamping events or showing date/times, among many...

3 minutes read.