×

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

Java vs Go

Java: Java is an object oriented programming language. It is also known as multi threaded language. It was designed by James gosling in the year 1995. We can also say that...

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

Java Trim

Leading and leaving spaces are removed by the built-in Java String trim() method. Space seems to have the Unicode element of "x0040." Java trim() function looks for all of these...

3 minutes read.

Types of JDBC Drivers

JDBC Drivers: A piece of software known as JDBC Driver permits database communication between Java applications and the server. In order to communicate with our database server, JDBC drivers put into practice...

4 minutes read.

Java vs Scala

Java : Java is an object oriented programming language. It is also known as multi threaded language. It was designed by James gosling in the year 1995. We can also say...

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 Code Coverage Tools

Code coverage testing is a crucial metric that gauges how thoroughly the program's source code has been tested. The market is flooded with Code Coverage Tools, making it difficult to...

7 minutes read.

Java Generics Questions

Introduction We'll walk through a few real-world examples of interview questions and responses for Java generics in this article. Java 5 saw the debut of the fundamental idea of generics. Due to...

9 minutes read.

How to Convert Octal to Decimal in Java

How to Convert Octal to Decimal in Java There are two methods to convert Octal to Decimal: Using parseInt() method Using user-defined logic Using Integer.parseInt() method The Integer.parseInt() method is a static method...

2 minutes read.

Java try catch

Java try catch There can be statements that can cause exceptions, and the exception leads to abnormal termination of the program. To avoid that abnormal termination, those statements that look potent...

4 minutes read.

Frugal number in Java

A frugal number is a positive integer with base b that has more digits than the number of prime factors it can be factored into (including exponents greater than 1)....

3 minutes read.

Java String toUpperCase() methods

Java String toUpperCase() method is used to convert all the characters of the String into upper case. Syntax public String toUpperCase() public String toUpperCase(Locale locale) Returns It returns upper case String. Java String toUpperCase() Example 1: public...

1 minute read.

Java While Keyword

Depending on a specified Boolean condition, a while loop in Java allows code to be executed repeatedly. The while loop can be viewed as an iterative version of the if...

3 minutes read.

C# vs Java

Difference Between C# and Java C# and Java both languagesare popularly used programming languages. They both are derived from C/C++ programming and follow Object Oriented Programming approach. Even so, both these...

4 minutes read.

Bad Operand types for Binary Operator Java

We will discuss how to handle issues in bad operand types for binary operator &, bad operand types for binary operator &&, bad operand types for binary operator ==, and...

4 minutes read.

Stable Marriage Problem in Java

Given N men and N women, the Stable Marriage Problem asks you to match up the men and women in such a way that there are never any two people...

6 minutes read.

Method Overriding in Java

Overriding  Overriding is also known as run time polymorphism, and it is about the same method with the same signatures in different classes. Overriding can be applied only methods. Method Overriding Method Overriding...

8 minutes read.

Conditional operator in Java

In Java, there are around eight operators, and among them, three operators are used to evaluate the condition and decide the Result based on the Result of the evaluated condition. Below...

4 minutes read.

Types of Events in Java

One of Java's key ideas is the principle of an event. Events in Java are activities that result in a change in the state or behavior of an object. The...

4 minutes read.

Java Break Keyword

Break: The word Break is a keyword or a statement in a java programming language.This Keyword break is used to stop the execution of the loop or switch statements etc.The loop...

3 minutes read.