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.

Example of Methods in Java

Types of Methods in Java

1. Instance Methods

Operate on instance variables

2. Static Methods

Belong to the class, not objects

3. Abstract Methods

Declared without implementation in an abstract class

4. Final Methods

Cannot be overridden

5. Synchronized Methods

Used in multithreading

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

Types of Fields in Java

1. Instance Fields

Unique to each object

2. Static Fields

Shared among all objects

3. Final Fields

Cannot be reassigned

4. Transient Fields

Ignored during serialization

5. Volatile Fields

Used in multithreading to ensure consistency

Last updated