1.1 Basic Structure Of A Java Class

Basic Structure of a Java Class

A Java class is the blueprint or template for creating objects. It defines the properties and behaviors that an object of that class will have. Here are the basic components of a Java class:

Class Declaration

A class is declared using the class keyword followed by the class name. The class name should start with an uppercase letter and follow the CamelCase convention.

public class MyClass {
    // class members
}

Class Members

A class can have two types of members: fields (variables) and methods.

Fields

Fields represent the state or data of an object. They can be of any data type and can have different access modifiers (public, private, etc.). Fields are declared within the class but outside of any method.

public class MyClass {
    private int myField; // private field
    public String name; // public field
}

Methods

Methods define the behavior or actions that an object can perform. They consist of a method signature (return type, name, and parameters) and a method body (code block).

public class MyClass {
    public void myMethod() {
        // method body
    }
    
    public int sum(int a, int b) {
        return a + b;
    }
}

Constructors

Constructors are special methods used to initialize objects of a class. They have the same name as the class and do not have a return type. Constructors are called using the new keyword when creating an object.

public class MyClass {
    public MyClass() {
        // constructor body
    }
}

Main Method

The main method is the entry point of a Java program. It is a special method that is called when the program starts. It has a specific signature and is declared as public static void main(String[] args).

public class MyClass {
    public static void main(String[] args) {
        // main method body
    }
}

These are the basic components that make up the structure of a Java class. Understanding this structure is essential for creating and working with Java objects.