Classes, objects and methods in Java
Definitions, syntax, and examples for Java classes, objects, fields and methods, including object creation, access control, method calling, parameter passing, and basic object behavior (toString, equals), with runnable programs.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Engineers model real-world entities (bank accounts, sensors, employees) as software using classes and objects. Understanding classes, objects, and methods in Java lets you design clean, reusable code, test behavior in isolation, and reason about program state in large systems.
Key ideas
- Object (instance): An object is a runtime entity created from a class. Exact statement: “An object is an instance of a class, occupying memory, with its own state (field values) and the methods defined by its class.” Assumption: objects are accessed via references in Java.
- Reference: A reference is a variable that stores a reference (pointer-like handle managed by the JVM) to an object, not the object itself. Exact statement: “In Java, variables of class type store references, not objects themselves.” Consequence: assignment copies the reference, not the object; null is a valid reference meaning “no object”.
- Field (instance variable): A field is a named variable inside a class that holds part of an object’s state. Exact statement: “Instance fields belong to each object; each object has its own copy.” Access via the dot operator on an object reference. Units: not applicable in programming; name, type, and visibility (modifier) define each field.
- Method: A method is a named block of code in a class that can be called to perform an action or compute a value. Exact statement: “A method has a return type (or void), a name, a parameter list (possibly empty), a body, and optionally modifiers.” A method’s behavior operates on an object’s fields (for instance methods) or only on parameters/local variables (for static methods, covered elsewhere).
- Method signature: The signature is the method name plus the ordered list of parameter types. Exact statement: “In Java, a method’s signature is its name and parameter types; the return type is not part of the signature.” Assumption: used to resolve method calls and overloading (detailed under Method overloading topic).
- Access modifiers: These control visibility and encapsulation. Exact statement: “public: accessible from anywhere; private: accessible only within the same class; protected: accessible within the same package and in subclasses; package-private (no modifier): accessible within the same package.” Assumption: packages group related classes (see Packages and the Java API topic).
- Encapsulation: Encapsulation is the practice of hiding internal state and exposing behavior through methods. Exact definition: “Encapsulation bundles data with methods and restricts direct access to some of an object’s components.” Typical pattern: private fields + public getters/setters + validation.
- this keyword: this refers to the current object inside an instance method or constructor. Exact statement: “this is a reference to the current instance; used to access fields shadowed by parameters, to call other constructors, or to pass the current object as an argument.” Note: this cannot be used in a static context.
- Constructor (overview only): A constructor is a special method-like block used to create and initialize objects of a class; it has the same name as the class and no return type. If no constructor is declared, the compiler provides a default no-argument constructor; if any constructor is declared, no default is generated. Details are in Constructors, this and static members.
- Object creation: Objects are created with new, which allocates memory, runs the constructor, and returns a reference. Example: Rectangle r = new Rectangle(3.0, 4.0);
- Dot operator (.): Used to access fields and methods of an object or class. Example: r.area(); r.width.
- Return value: A method can return a value using return expression;. If the method’s return type is void, return; is optional to exit early.
- Parameter passing: Exact statement: “Java is strictly pass-by-value.” For primitives, the value is copied; for references, the reference itself is copied (so the method can mutate the object’s fields via the copied reference, but reassigning the parameter does not affect the caller’s reference). Assumption: students understand primitive vs reference types.
- Method overloading vs overriding (orientation only): Overloading is multiple methods with the same name but different parameter lists in the same class (covered under Method overloading). Overriding is redefining an inherited method in a subclass (covered under Inheritance in Java and Abstract classes, final and dynamic binding).
- toString(): Returns a string representation of the object; used implicitly in string concatenation and printing. Good practice: override toString() to produce human-readable output.
- equals(Object): Tests logical equality. Exact statement: “The equals contract requires reflexive, symmetric, transitive, consistent behavior, and x.equals(null) must be false.” If you override equals, also override hashCode consistently. (hashCode and collections are treated in Packages and the Java API; only the connection is noted here.)
- Immutability (orientation only): An immutable class has objects whose state cannot change after construction. Benefits: thread-safety and simpler reasoning. Implementation details are covered in related topics; here we only connect to method design (e.g., return new objects rather than mutating).
Diagram to draw and label (if asked): “Class diagram sketch for a simple class” — Draw a box with three compartments stacked vertically. Top: Class name (e.g., Rectangle). Middle: list fields with types (e.g., - width: double, - height: double; minus sign to denote private if using UML notation). Bottom: list methods with parameter and return types (e.g., + area(): double, + perimeter(): double). Label the box ‘Class Rectangle’. Then draw an ‘object’ box: a rectangle with ‘:Rectangle’ and example field values (width=3.0, height=4.0). Draw an arrow labeled ‘reference r’ from a small variable box named r to the object box to indicate a reference variable pointing to an object.
Formulas
Type variableName;— Declaring a reference variable (Type is a class name).variableName = new ClassName(arguments);— Object creation with constructor call; new allocates and returns a reference.Type variableName = new ClassName(arguments);— Declaration and creation together (common pattern).accessModifier class ClassName { ... }— Access modifiers: public or package-private (no modifier) on top-level classes. At most one public top-level class is allowed per .java file, and the filename must match the public class name.accessModifier type fieldName;— Field declaration; use private for encapsulation.accessModifier returnType methodName(parameterList) { /* body */ }— Method declaration.objectRef.fieldName— Accessing a field via dot.objectRef.methodName(arguments)— Calling an instance method via dot.return expression;— Returning a value from a non-void method;return;for early exit in void method.this.fieldName— Access current object’s field to avoid shadowing.this(otherArgs)— Constructor chaining (call another constructor of the same class; must be first statement). Details in Constructors, this and static members.@Override— Annotation before a method to indicate it overrides a superclass method (used with toString, equals in practice).public String toString() { ... }— Override toString to provide a readable representation.public boolean equals(Object o) { ... }— Override equals to provide logical equality.
Worked examples
Example 1: Class, objects and methods without input Complete Java program:
// Example 1: Rectangle class with methods
class Rectangle {
private double width;
private double height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
public double getWidth() { return width; }
public double getHeight() { return height; }
public double area() {
return width * height;
}
public double perimeter() {
return 2 * (width + height);
}
public void scale(double factor) {
if (factor <= 0) {
throw new IllegalArgumentException("Scale factor must be positive");
}
width *= factor;
height *= factor;
}
@Override
public String toString() {
return "Rectangle{" + "width=" + width + ", height=" + height + '}';
}
}
public class Main1 {
public static void main(String[] args) {
Rectangle r = new Rectangle(3.0, 4.0);
System.out.println("Created: " + r);
System.out.println("Area = " + r.area());
System.out.println("Perimeter = " + r.perimeter());
r.scale(2.0);
System.out.println("After scaling by 2: " + r);
System.out.println("Area = " + r.area());
System.out.println("Perimeter = " + r.perimeter());
}
}
Sample input:
- No input
Exact output:
Created: Rectangle{width=3.0, height=4.0}
Area = 12.0
Perimeter = 14.0
After scaling by 2: Rectangle{width=6.0, height=8.0}
Area = 48.0
Perimeter = 28.0
Example 2: Reading input, creating objects, and invoking methods Complete Java program:
// Example 2: Simple BankAccount with deposits and withdrawals
import java.util.Scanner;
class BankAccount {
private int accountNumber;
private String holderName;
private double balance;
public BankAccount(int accountNumber, String holderName, double balance) {
this.accountNumber = accountNumber;
this.holderName = holderName;
this.balance = balance;
}
public boolean deposit(double amount) {
if (amount <= 0) return false;
balance += amount;
return true;
}
public boolean withdraw(double amount) {
if (amount <= 0 || amount > balance) return false;
balance -= amount;
return true;
}
public double getBalance() { return balance; }
public int getAccountNumber() { return accountNumber; }
public String getHolderName() { return holderName; }
}
public class Main2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int accNo = sc.nextInt();
String name = sc.next();
double initial = sc.nextDouble();
int n = sc.nextInt();
BankAccount acc = new BankAccount(accNo, name, initial);
System.out.printf("Created account %d for %s with balance %.2f%n", acc.getAccountNumber(), acc.getHolderName(), acc.getBalance());
for (int i = 0; i < n; i++) {
String cmd = sc.next();
double amt = sc.nextDouble();
switch (cmd) {
case "DEPOSIT":
boolean dep = acc.deposit(amt);
if (dep) {
System.out.printf("After DEPOSIT %.2f, balance = %.2f%n", amt, acc.getBalance());
} else {
System.out.printf("Deposit of %.2f failed.%n", amt);
}
break;
case "WITHDRAW":
boolean ok = acc.withdraw(amt);
if (ok) {
System.out.printf("After WITHDRAW %.2f, balance = %.2f%n", amt, acc.getBalance());
} else {
System.out.printf("Withdrawal of %.2f failed (insufficient funds).%n", amt);
}
break;
default:
System.out.println("Unknown command");
}
}
System.out.printf("Final balance: %.2f%n", acc.getBalance());
sc.close();
}
}
Sample input:
1001
Asha
1000.00
3
DEPOSIT 500.00
WITHDRAW 200.50
WITHDRAW 900.00
Exact output:
Created account 1001 for Asha with balance 1000.00
After DEPOSIT 500.00, balance = 1500.00
After WITHDRAW 200.50, balance = 1299.50
After WITHDRAW 900.00, balance = 399.50
Final balance: 399.50
Example 3: Parameter passing — primitives vs references Complete Java program:
// Example 3: Demonstrate Java pass-by-value on primitives and references
class Counter {
int value;
Counter(int value) { this.value = value; }
@Override public String toString() { return "Counter{" + value + '}'; }
}
public class Main3 {
static void incrementNumber(int x) {
x = x + 1; // modifies only local copy
}
static void modifyCounter(Counter c) {
c.value = c.value + 1; // changes the object via the copied reference
}
static void reassignCounter(Counter c) {
c = new Counter(999); // reassigns local parameter only; caller unaffected
}
public static void main(String[] args) {
int a = 10;
incrementNumber(a);
System.out.println("After incrementNumber, a = " + a);
Counter ctr = new Counter(10);
modifyCounter(ctr);
System.out.println("After modifyCounter, ctr = " + ctr);
reassignCounter(ctr);
System.out.println("After reassignCounter, ctr = " + ctr);
}
}
Sample input:
- No input
Exact output:
After incrementNumber, a = 10
After modifyCounter, ctr = Counter{11}
After reassignCounter, ctr = Counter{11}
Explanation: Java passes by value. For a primitive, the value is copied; changing x does not change a. For a reference, the reference is copied; changing the object’s field via the copied reference affects the original object. Reassigning the parameter to a new object only changes the local copy of the reference, leaving the caller’s reference unchanged.
Common mistakes
- Accessing private fields directly from outside the class — breaks encapsulation; use getters/setters or suitable methods.
- Forgetting to initialize objects with new — declaring a reference does not create an object; using a null reference causes NullPointerException.
- Comparing objects using == when logical equality is intended — == compares references; use equals for content-based comparison.
- Not overriding toString, leading to unreadable output (ClassName@hashcode) in debugging or exam outputs.
- Mixing nextInt/nextDouble with nextLine without handling newline — can cause skipped inputs. Prefer token-based input consistently or consume the newline explicitly (relevant to Example 2 design).
- Writing return in a void method with a value — compile-time error; either return; only, or specify a non-void return type.
- Using floating-point for money without formatting — leads to outputs like 1299.5; in exam code, format with printf. (For production financial code, BigDecimal is preferred; outside this topic.)
For your exam
- Short notes: parameter passing in Java (with a diagram of variable, reference, and object), toString and equals purpose, difference between == and equals, dot operator usage.
- Diagrams: UML-style class diagram showing fields, methods, and an object instance with a reference variable pointing to it; label access (public/private) clearly.
- Programs: implement a simple class with fields (private), constructor(s), methods (area/perimeter, deposit/withdraw), and a main to create objects and call methods. Full marks: correct encapsulation, correct method signatures, correct outputs, and comments or clear prints.
- Tracing/execution: given a code snippet, predict the output, especially around pass-by-value and method calls. Full marks: show step-by-step state changes of variables and objects.
- Reasoning: why use getters/setters instead of public fields; how access modifiers enforce encapsulation. Full marks: connect to maintainability, validation, and invariants.
Quick check
- State the definition of a class and an object in Java.
- What does Java pass to methods: the object itself, or a copy of the reference? What is the effect?
- Why should equals usually be overridden when you override toString for a value-like class?
Answers: 1) A class defines data and methods; an object is a runtime instance of a class with its own state. 2) A copy of the reference (pass-by-value); methods can mutate the object via that reference, but reassigning the parameter does not affect the caller. 3) For logical equality of objects with the same content; equals enables correct comparisons and collection behavior consistent with the textual representation.
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?