Master classes and records, instance and static fields and methods, constructors, initializers, overloaded methods, and var-arg methods for the OCP 21 exam.
Table of Contents
1. Classes
A class is a blueprint for creating objects. It defines the structure and behavior that objects of that class will have.
1.1 Class Declaration
// Basic class declaration class Person {
// Fields String name;
int age;
// Methods void speak() {
System.out.println("Hello, I'm" + name);
}
} // Class with access modifier public class Student {
private String id;
public String name;
public void study() {
System.out.println("Studying...");
}
} // Final class (cannot be extended) final class Utility {
// Utility methods } // Abstract class (cannot be instantiated) abstract class Animal {
abstract void makeSound();
}
1.2 Class Components
- Fields: Variables that hold object state
- Methods: Functions that define object behavior
- Constructors: Special methods for object initialization
- Initializers: Blocks of code that run during object creation
- Nested Classes: Classes defined inside other classes
2. Records (Java 14+)
Records (introduced in Java 14, finalized in Java 16) are immutable data carriers that automatically generate constructors, getters, equals(), hashCode(), and toString().
2.1 Record Declaration
// Basic record record Point(int x, int y) {
} // Using the record Point p1 = new Point(10, 20);
Point p2 = new Point(10, 20);
System.out.println(p1.x());
// 10 (accessor method) System.out.println(p1.equals(p2));
// true (auto-generated) System.out.println(p1);
// Point[x=10, y=20] (toString) // Record with additional methods record Person(String name, int age) {
// Compact constructor (validation) public Person {
if (age < 0) {
throw new IllegalArgumentException("Age cannot be negative");
}
} // Additional method public boolean isAdult() {
return age >= 18;
} // Static method public static Person create(String name) {
return new Person(name, 0);
}
} // Record with custom constructor record Rectangle(int width, int height) {
// Canonical constructor public Rectangle(int width, int height) {
this.width = width;
this.height = height;
} // Custom constructor public Rectangle(int side) {
this(side, side);
// Square }
}
2.2 Record Features
- All fields are
final(immutable) - Automatically generates accessor methods (not getters)
- Automatically generates
equals(),hashCode(),toString() - Can implement interfaces
- Can have static fields and methods
- Cannot extend other classes (implicitly extends Record)
3. Fields
Fields are variables that hold the state of an object or class.
3.1 Instance Fields
class Person {
// Instance fields (each object has its own copy) String name;
int age;
boolean isActive;
void display() {
System.out.println(name +"," + age);
}
} Person p1 = new Person();
p1.name ="Alice";
// p1's name p1.age = 30;
Person p2 = new Person();
p2.name ="Bob";
// p2's name (independent) p2.age =
25;
3.2 Static Fields
class Counter {
// Static field (shared by all instances) static int count = 0;
// Instance field int instanceCount;
Counter() {
count++;
// Increment shared counter instanceCount++;
// Increment instance counter }
} Counter c1 = new Counter();
// count = 1 Counter c2 = new Counter();
// count = 2 Counter c3 = new Counter();
// count = 3 System.out.println(Counter.count);
// 3 (accessed via class) System.out.println(c1.count);
// 3 (accessed via instance, not recommended) System.out.println(c1.instanceCount);
// 1 (each instance has own
copy)
3.3 Field Modifiers
| Modifier | Description |
|---|---|
| private | Accessible only within the class |
| protected | Accessible within package and subclasses |
| public | Accessible from anywhere |
| (package-private) | Accessible within the same package |
| final | Cannot be reassigned after initialization |
| static | Belongs to class, not instance |
4. Methods
Methods define the behavior of a class. They can be instance methods or static methods.
4.1 Instance Methods
class Person {
String name;
int age;
// Instance method (operates on instance) void display() {
System.out.println(name +"," + age);
} // Instance method with return value String getName() {
return name;
} // Instance method with parameters void setAge(int newAge) {
age = newAge;
} // Instance method accessing instance fields boolean isAdult() {
return age >= 18;
}
} Person person = new Person();
person.name ="Alice";
person.display();
// Called on instance person.setAge(30);
// Called on
instance
4.2 Static Methods
class MathUtils {
// Static method (belongs to class) static int add(int a, int b) {
return a + b;
}
static double calculateArea(double radius) {
return Math.PI * radius * radius;
} // Cannot access instance fields/methods // static void badMethod() {
// System.out.println(name);
// Compilation error! // }
} // Called via class name int result = MathUtils.add(5, 3);
double area = MathUtils.calculateArea(5.0);
// Can also be called via instance (not recommended) MathUtils utils = new MathUtils();
int result2 = utils.add(5, 3);
// Works but not
recommended
5. Constructors
Constructors are special methods used to initialize objects. They have the same name as the class and no return type.
5.1 Default Constructor
class Person {
String name;
int age;
// Default constructor (provided by compiler if none defined) // Person() {
// super();
// }
} Person person = new Person();
// Uses default
constructor
5.2 Parameterized Constructor
class Person {
String name;
int age;
// Parameterized constructor Person(String name, int age) {
this.name = name;
this.age = age;
} // Multiple constructors (overloading) Person(String name) {
this(name, 0);
// Calls other constructor }
Person() {
this("Unknown", 0);
// Calls parameterized constructor }
} Person p1 = new Person("Alice", 30);
Person p2 = new Person("Bob");
Person p3 = new Person();
5.3 Constructor Chaining
class Person {
String name;
int age;
String email;
Person(String name, int age, String email) {
this.name = name;
this.age = age;
this.email = email;
}
Person(String name, int age) {
this(name, age, null);
// Chain to 3-parameter constructor }
Person(String name) {
this(name, 0, null);
// Chain to 3-parameter constructor }
}
6. Initializers
Initializers are blocks of code that execute during object or class initialization.
6.1 Instance Initializers
class Example {
int value;
// Instance initializer (executes before constructor) {
System.out.println("Instance initializer");
value = 10;
}
Example() {
System.out.println("Constructor");
value = 20;
}
} // Output when creating object: // Instance initializer // Constructor Example obj = new Example();
// value is 20 (constructor
overrides)
6.2 Static Initializers
class Example {
static int count;
// Static initializer (executes once when class is loaded) static {
System.out.println("Static initializer");
count = 100;
} // Multiple static initializers static {
count++;
// Executes in order }
} // Static initializer executes when class is first accessed System.out.println(Example.count);
// 101
6.3 Initialization Order
- Static fields and static initializers (in order)
- Instance fields and instance initializers (in order)
- Constructor
7. Method Overloading
Method overloading allows multiple methods with the same name but different parameters.
7.1 Overloading Rules
- Methods must have the same name
- Parameter lists must differ in:
- Number of parameters
- Type of parameters
- Order of parameters
- Return type doesn't matter for overloading
- Access modifiers don't matter for overloading
class Calculator {
// Different number of parameters int add(int a, int b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
} // Different parameter types double add(double a, double b) {
return a + b;
} // Different order void display(String name, int age) {
System.out.println(name +"," + age);
}
void display(int age, String name) {
System.out.println(age +"," + name);
} // Return type doesn't matter int multiply(int a, int b) {
return a * b;
} // double multiply(int a, int b) {
// Compilation error - same signature // return a * b;
// }
} Calculator calc = new Calculator();
calc.add(5, 3);
// Calls int add(int, int) calc.add(5.0, 3.0);
// Calls double add(double, double) calc.add(1, 2, 3);
// Calls int add(int, int,
int)
8. Var-Arg Methods
Var-args (variable arguments) allow methods to accept a variable number of arguments.
8.1 Var-Args Syntax
class Calculator {
// Var-args method (must be last parameter) int sum(int... numbers) {
int total = 0;
for (int num : numbers) {
total += num;
}
return total;
} // Var-args with other parameters void print(String prefix, int... values) {
System.out.print(prefix +":");
for (int val : values) {
System.out.print(val +"");
}
System.out.println();
} // Can have zero arguments void method(String... args) {
System.out.println("Number of arguments:" + args.length);
}
} Calculator calc = new Calculator();
calc.sum(1, 2, 3);
// 6 calc.sum(1, 2, 3, 4, 5);
// 15 calc.sum();
// 0 (zero arguments) calc.print("Numbers", 1, 2, 3);
// Numbers: 1 2 3 calc.method();
// Number of arguments:
0
8.2 Var-Args Rules
- Var-args parameter must be the last parameter
- Only one var-args parameter per method
- Var-args is treated as an array
- Can pass an array to var-args method
// Passing array to var-args int[] numbers = {1, 2, 3, 4, 5};
int result = calc.sum(numbers);
// Works! // Var-args with overloading void method(int... nums) {
}
void method(int a, int... nums) {
} // Valid - different signature // void method(int... nums, String s) {
} // Invalid - var-args must be
last
9. Exam Key Points
Critical Concepts for OCP 21 Exam:
- Class: Blueprint for objects, contains fields and methods
- Record: Immutable data carrier (Java 14+), auto-generates methods
- Instance Fields: Each object has its own copy
- Static Fields: Shared by all instances, belongs to class
- Instance Methods: Operate on instance, can access instance fields
- Static Methods: Belong to class, cannot access instance members
- Default Constructor: Provided by compiler if none defined
- Constructor Chaining:
Use
this()to call other constructor - Instance Initializer: Executes before constructor for each object
- Static Initializer: Executes once when class is loaded
- Initialization Order: Static → Instance → Constructor
- Method Overloading: Same name, different parameters (number, type, order)
- Return Type: Doesn't matter for overloading
- Var-Args:
type... name, must be last parameter - Var-Args Array: Var-args is treated as array, can pass array
- Record Fields:
All final, accessors are
fieldName()notgetFieldName() - Record Immutability: Records are immutable, cannot extend classes
- Compact Constructor: Record constructor without parameters (validation)
0 Comments