Java Methods & Classes
Methods, static & Constructors
How Java packages behavior — typed methods, overloading, the static/instance split, and the constructors that build objects.
Java 21
3 Topics
01
Methods & Overloading
Every Java method declares a return type and typed parameters. Overloading lets several methods share one name as long as their parameter lists differ — the compiler picks the right one by the arguments you pass.
Java — Methods, Overloading, varargs
// returnType name(params) { body } int add(int a, int b) { return a + b; } // Overloading — same name, different parameter types double add(double a, double b) { return a + b; } String add(String a, String b) { return a + b; } // varargs — accept any number of arguments int sum(int... nums) { // nums is an int[] int total = 0; for (int n : nums) total += n; return total; } sum(1, 2, 3, 4); // 10 sum(); // 0 — zero args is fine
Overloads must differ in parameter types or count, not just return type.
int f() and double f() is a compile error — the compiler can't choose based on return type alone.02
static vs Instance
A static member belongs to the class itself — one copy, shared by everyone. An instance member belongs to each object, with its own separate value per instance.
Java — static vs instance
class Counter { static int total = 0; // shared across ALL Counter objects int id; // unique to each object Counter() { total++; // increments the shared count id = total; // this object's own id } static int getTotal() { return total; } // called on the class } new Counter(); new Counter(); new Counter(); Counter.getTotal(); // 3 — no object needed to call a static method
main is static because the JVM calls it before any object exists. Utility methods like Math.sqrt() are static for the same reason — they don't need an instance to do their job.03
Classes & Constructors
A constructor is a special method with the class's name and no return type. It runs when you write new, and its job is to initialize the object's fields. this refers to the object being built.
Java — Constructors & this
class Point { int x, y; Point(int x, int y) { // constructor — same name as class this.x = x; // this.x = the field, x = the parameter this.y = y; } Point() { // overloaded constructor — origin this(0, 0); // calls the other constructor } public String toString() { return "(" + x + ", " + y + ")"; } } Point p = new Point(3, 4); System.out.println(p); // (3, 4) — toString() auto-called
✓
Quick Quiz
1. Overloaded methods must differ in…
2. A static member belongs to…
3. Why is main declared static?
4. A constructor's return type is…
5. Inside a constructor, this(0, 0) does what?