Methods & Fields

About Method

A method in Java is a block of code that performs a specific task. Methods define the behavior of a class and are used to operate on data (fields).

Characteristics of a Method

  1. Encapsulates Behaviour

    • A method contains reusable logic that can be called multiple times.

  2. Has a Signature

    • In Java, a method signature consists ONLY of the method name and parameter list (type, order, and number of parameters).

    • Return type and access modifiers are NOT part of the method signature.

    • Example:

      public int add(int a, int b) { return a + b; }
  3. Can Take Parameters

    • Methods can accept input values (parameters).

    • Example:

      void greet(String name) { System.out.println("Hello, " + name); }
  4. Can Return a Value

    • A method may return a value using return.

    • Example:

      int square(int num) { return num * num; }
    • If no value is returned, the return type is void.

      void display() { System.out.println("No return value"); }
  5. Access Modifiers

    • Determines method visibility (public, private, protected, or package-private).

Why is Return Type NOT Part of the Method Signature?

Java does not allow method overloading based only on return type.

int getValue() { return 10; }
double getValue() { return 10.5; }  // Compilation error (Same signature: `getValue()`)

Example of Methods in Java

class Calculator {
    // Method without parameters
    void greet() {
        System.out.println("Welcome to Calculator!");
    }

    // Method with parameters and return type
    int add(int a, int b) {
        return a + b;
    }

    // Method with no return (void)
    void printResult(int result) {
        System.out.println("Result: " + result);
    }
}

public class Main {
    public static void main(String[] args) {
        // Creating an object
        Calculator calc = new Calculator();

        // Calling methods
        calc.greet();
        int sum = calc.add(5, 10);
        calc.printResult(sum);
    }
}

/* Output:
Welcome to Calculator!
Result: 15
*/

Types of Methods in Java

1. Instance Methods

Operate on instance variables

class Person {
    String name;
    void setName(String name) { this.name = name; }
}

2. Static Methods

Belong to the class, not objects

class MathUtil {
    static int square(int x) { return x * x; }
}

// Usage:
// int result = MathUtil.square(4);

3. Abstract Methods

Declared without implementation in an abstract class

abstract class Animal {
    abstract void makeSound();  // No implementation
}

4. Final Methods

Cannot be overridden

class Parent {
    final void show() { System.out.println("Cannot be overridden"); }
}

5. Synchronized Methods

Used in multithreading

class SharedResource {
    synchronized void access() { System.out.println("Thread-safe"); }
}

About Field

A field in Java (also called an instance variable or attribute) is a variable declared inside a class. It represents the state or properties of an object.

Local variable and Instance variable

Characteristics of a Field

  1. Stores Object Data

    • Fields hold values that define the object's state.

  2. Can Have Different Access Levels

    • Controlled by access modifiers (private, public, protected, package-private).

  3. Can Have Default Values

    • Primitive types (e.g., int defaults to 0, boolean to false).

    • Reference types (e.g., String defaults to null).

  4. Can Be Static or Final

    • static fields belong to the class, not individual objects.

    • final fields cannot be changed after initialization.

Example of Fields in Java

class Car {
    // Instance fields
    String brand;
    int speed;

    // Static field
    static int wheels = 4;

    // Constructor
    Car(String brand, int speed) {
        this.brand = brand;
        this.speed = speed;
    }

    // Method to display details
    void showDetails() {
        System.out.println(brand + " is moving at " + speed + " km/h.");
    }
}

public class Main {
    public static void main(String[] args) {
        Car car1 = new Car("Toyota", 60);
        Car car2 = new Car("Honda", 50);

        car1.showDetails(); // Toyota is moving at 60 km/h.
        car2.showDetails(); // Honda is moving at 50 km/h.

        // Accessing a static field
        System.out.println("Cars have " + Car.wheels + " wheels.");
    }
}

/* Output:
Toyota is moving at 60 km/h.
Honda is moving at 50 km/h.
Cars have 4 wheels.
*/

Types of Fields in Java

1. Instance Fields

Unique to each object

class Dog {
    String name;  // Each dog has its own name
}

2. Static Fields

Shared among all objects

class School {
    static String schoolName = "Greenwood High";
}

// Usage:
System.out.println(School.schoolName);

3. Final Fields

Cannot be reassigned

class Person {
    final String country = "USA";  // Cannot be changed
}

4. Transient Fields

Ignored during serialization

class User {
    transient String password;  // Not stored when saving an object
}

5. Volatile Fields

Used in multithreading to ensure consistency

class SharedData {
    volatile boolean flag = true;
}

Last updated

Was this helpful?