Class
A class serves as an abstract representation of entities sharing common attributes and behaviors in the real world. It defines a blueprint for creating objects, specifying their data (instance variables) and operations (methods). Key characteristics include:
- Abstraction: Models essential features while omitting irrelevant details.
- Template Role: Acts as a mold for generating objects with consistent structure.
- Encapsulation: Bundles data and methods, hiding internal implementation behind controlled interfaces.
- Inheritance Support: Enables hierarchical relationships where subclasses inherit and extend superclas features.
- Polymorphic Behavior: Allows uniform interaction with diverse object types through shared interfaces.
Object
An object is a concrete instance of a class, embodying unique state and executable behavior. Core attributes:
- Instance Identity: Each object occupies distinct memory space, identified by a unique address.
- State Representation: Defined by current values of its instance variables (e.g., a vehicle's color or speed).
- Behavior Execution: Invokes class-defined methods to perform actions (e.g., starting or stopping).
- Interoperability: Communicates with other objects via method calls (message passing).
Illustrative Example
Consider a Vehicle class modeling basic automotive properties and actions:
public class Vehicle {
// Instance variables
private String paintColor;
private int currentSpeed;
// Constructor
public Vehicle(String paintColor) {
this.paintColor = paintColor;
this.currentSpeed = 0;
}
// Methods
public void ignite() {
currentSpeed = 10; // Initial movement
System.out.println(paintColor + " vehicle ignited.");
}
public void halt() {
currentSpeed = 0;
System.out.println(paintColor + " vehicle halted.");
}
public String getPaintColor() {
return paintColor;
}
}
Creating and using a Vehicle object:
public class Demo {
public static void main(String[] args) {
Vehicle userVehicle = new Vehicle("Blue"); // Instantiate
userVehicle.ignite(); // Output: Blue vehicle ignited.
System.out.println("Color: " + userVehicle.getPaintColor());
userVehicle.halt(); // Output: Blue vehicle halted.
}
}
Here, Vehicle is the class (template), and userVehicle is an object (instance) with state (paintColor="Blue", currentSpeed=0) and behavior (ignite, halt).
Instance Variables
Instance variables (attributes/fields) store an object's state within a class. Key traits:
- Scope: Accessible across all class methods.
- Encapsulation: Typically
private, accessed/modified via public getters/setters. - Initialization: Set at declaration, in constructors, or via setters.
- Types: Primitive (e.g.,
int) or referance (e.g.,String).
Access Modifiers
public: Unrestricted access.private: Class-internal only.protected: Class, subclasses, and same-package classes.- Default (no modifier): Same-package access.
Example
public class Employee {
private String fullName; // Private: requires getter/setter
protected int yearsOfService; // Protected: subclass-accessible
public double bodyHeight; // Public: direct access
public Employee(String fullName, int years, double height) {
this.fullName = fullName;
this.yearsOfService = years;
this.bodyHeight = height;
}
// Getter/Setter for fullName
public String getFullName() { return fullName; }
public void setFullName(String fullName) { this.fullName = fullName; }
}
Member Methods
Methods define object behavior, categorized as:
- Instance Methods: Operate on object state (require instantiation).
- Static Methods: Belong to the class (invoked via class name, no instance needed).
- Constructors: Special methods initializing new objects (same name as class, no return type).
Features
- Overloading: Multiple methods with same name, different parameters.
- Overriding: Subclasses redefining superclass methods.
- Access Control: Modifiers (
public/private) restrict visibility.
Example
public class Vehicle {
private String model;
private int currentSpeed;
// Constructor
public Vehicle(String model) {
this.model = model;
this.currentSpeed = 0;
}
// Instance method
public void increaseSpeed(int increment) {
currentSpeed += increment;
System.out.println(model + " speed: " + currentSpeed + " km/h");
}
// Static method
public static void printSpecs() {
System.out.println("Vehicle specs available");
}
}
Object Instantiation via Constructors
Constructors initialize objects during creation. Types include:
Default Constructor
Automatically generated if no constructor is defined. Initializes variables to default values (e.g., 0, null).
public class Gadget {
private String id;
private boolean active;
// No explicit constructor: compiler adds default (Gadget() {})
}
// Usage
Gadget defaultGadget = new Gadget(); // id=null, active=false
Parameterized Constructor
Accepts arguments to set initial state.
public class Gadget {
private String id;
private boolean active;
public Gadget(String id, boolean active) {
this.id = id;
this.active = active;
}
}
// Usage
Gadget smartWatch = new Gadget("SW-2023", true);
Constructor Overloading
Multiple constructors with distinct parameter lists.
public class Gadget {
private String id;
private String brand;
private int releaseYear;
public Gadget() { // Default
this("Unknown", "Generic", 0);
}
public Gadget(String id, String brand) { // Partial init
this(id, brand, 2020);
}
public Gadget(String id, String brand, int year) { // Full init
this.id = id;
this.brand = brand;
this.releaseYear = year;
}
}
Using Objects
Basic operations:
- Creation:
ClassName obj = new ClassName(args); - Attribute Access:
obj.variable(if public) orobj.getter() - Method Invocation:
obj.method(args); - State Modification:
obj.setter(value); - Parameter/Return: Pass objects to methods or return them.
Example
public class DeviceDemo {
public static void main(String[] args) {
Device drone = new Device("Quadcopter-X", "AeroTech");
drone.activate(); // Output: Quadcopter-X activated
drone.updateFirmware(); // Output: Firmware updated
}
}
Automatic Memory Management via Garbage Collection
Garbage collectors (GC) automatically reclaim memory from unreferenced objects. Key aspects:
- Reference Tracking: Identifies unreachable objects (no active references).
- Algorithms: Mark-sweep, generational collection (young/old generations).
- Performance: May introduce brief pauses; modern GCs use concurrent/parallel strategies.
Example
public class GCDemo {
public static void main(String[] args) {
TempResource resource = new TempResource();
resource = null; // No references remain
// GC will eventually reclaim resource's memory
}
}
class TempResource { /* Resource data */ }
Anonymous Object Instances
Unnamed objects created for one-time use, often for immediate method calls or interface implementations.
Characteristics
- Ephemeral: No persistent reference; discarded after use.
- Convenience: Avoids named variable declarations.
- Common Use Cases: Callback implementations, single-method invocations.
Examples
// 1. Runnable thread
new Thread(new Runnable() {
public void run() { System.out.println("Anonymous thread running"); }
}).start();
// 2. Method argument
button.setListener(new ClickHandler() {
public void onClick() { System.out.println("Button clicked"); }
});
// 3. Direct method call
new Object() {
void log() { System.out.println("Anonymous log"); }
}.log();