Methods and Fields

Field Declarations

Instance Fields

public class Person {
    private String name;          // Instance field
    private int age = 0;          // With initializer
    private final String id;      // Must be initialized in constructor
}

Static Fields

public class Counter {
    private static int count = 0;           // Class variable
    public static final double PI = 3.14159; // Constant
}

Field Modifiers

ModifierDescription
privateOnly accessible within the class
protectedAccessible in class, subclasses, and package
publicAccessible from anywhere
staticShared across all instances
finalCannot be reassigned after initialization
volatileThread-safe reads/writes
transientNot serialized

Method Declarations

Basic Method Syntax

public class Calculator {
    // Instance method
    public int add(int a, int b) {
        return a + b;
    }

    // Static method
    public static int multiply(int a, int b) {
        return a * b;
    }

    // Void method
    public void printResult(int result) {
        System.out.println("Result: " + result);
    }
}

Method with Multiple Return Statements

public String classify(int n) {
    if (n < 0) return "negative";
    if (n == 0) return "zero";
    return "positive";
}

Varargs (Variable Arguments)

public int sum(int... numbers) {
    int total = 0;
    for (int n : numbers) {
        total += n;
    }
    return total;
}

// Usage
sum(1, 2, 3);
sum(1, 2, 3, 4, 5);

Generic Methods

public <T> T firstOrNull(T[] array) {
    if (array.length == 0) return null;
    return array[0];
}

public <T extends Comparable<T>> T max(T a, T b) {
    return a.compareTo(b) > 0 ? a : b;
}

Constructors

Basic Constructor

public class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

Constructor Overloading

public class Person {
    private String name;
    private int age;

    public Person() {
        this("Unknown", 0);
    }

    public Person(String name) {
        this(name, 0);
    }

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

Constructor Chaining with super

public class Employee extends Person {
    private String department;

    public Employee(String name, int age, String department) {
        super(name, age);  // Must be first statement
        this.department = department;
    }
}

Method Overloading

public class Printer {
    public void print(int n) {
        System.out.println("int: " + n);
    }

    public void print(double d) {
        System.out.println("double: " + d);
    }

    public void print(String s) {
        System.out.println("String: " + s);
    }

    public void print(int a, int b) {
        System.out.println("two ints: " + a + ", " + b);
    }
}

Method Overriding

public class Animal {
    public void speak() {
        System.out.println("Some sound");
    }
}

public class Dog extends Animal {
    @Override
    public void speak() {
        System.out.println("Woof!");
    }

    public void fetch() {
        super.speak();  // Call parent method
        System.out.println("Fetching...");
    }
}

Static Methods and Fields

Static Members

public class MathUtils {
    public static final double PI = 3.14159265359;

    public static int square(int n) {
        return n * n;
    }

    public static double circleArea(double radius) {
        return PI * radius * radius;
    }
}

// Usage - no instance needed
int sq = MathUtils.square(5);
double area = MathUtils.circleArea(2.0);

Static Initializers

public class Config {
    private static Map<String, String> settings;

    static {
        settings = new HashMap<>();
        settings.put("debug", "false");
        settings.put("version", "1.0");
    }
}

Instance Initializers

public class Person {
    private List<String> hobbies;

    {
        // Instance initializer - runs before every constructor
        hobbies = new ArrayList<>();
        hobbies.add("reading");
    }

    public Person() {
        // Constructor body runs after initializer
    }
}

Access Control

Modifier Class Package Subclass World
public Yes Yes Yes Yes
protected Yes Yes Yes No
default Yes Yes No No
private Yes No No No

The this Keyword

public class Person {
    private String name;

    public Person(String name) {
        this.name = name;  // Distinguish field from parameter
    }

    public Person withName(String name) {
        this.name = name;
        return this;  // Return current instance for chaining
    }
}

The super Keyword

public class Child extends Parent {
    public Child() {
        super();  // Call parent constructor
    }

    @Override
    public void method() {
        super.method();  // Call parent method
    }

    public void accessParent() {
        int value = super.field;  // Access parent field
    }
}