Implementing Classes and Objects in Java
Decoupled Class and Execution Patterns
Defining a class in a separate file from the execution logic is a standard practice that improves code maintainability. In this model, the blueprint (the class) and the instantiation (the main method) are isolated.
Account.java
package com.service.logic;
public class Account {
public String ownerName;
public boolean isPremium;
public int rewardPoints;
public void displayStats() {
System.out.println("Owner: " + ownerName);
System.out.println("Premium Member: " + isPremium);
System.out.println("Points: " + rewardPoints);
}
public void addSession(int duration) {
System.out.println("Active for: " + duration + " minutes");
}
public String generateReport(String tag, int code) {
String result = tag + "_" + code;
System.out.println("Generated: " + result);
return result;
}
}
Application.java
package com.service.logic;
public class Application {
public static void main(String[] args) {
Account user = new Account();
user.ownerName = "Alex";
user.rewardPoints = 500;
user.displayStats();
}
}
Single-File Multi-Class Structure
Java allows multiple classes within a single source file. Only one class can be declared as public, and it must correspond to the filename. Other classes serve as helper components within the same package scope.
ProcessManager.java
package com.service.core;
class Worker {
String workerId;
int level;
public void runTask(int mode) {
if (mode == 0) {
System.out.println("Executing baseline task...");
} else if (mode == 1) {
System.out.println("Executing priority task...");
return;
}
System.out.println("Task sequence finalized.");
}
}
public class ProcessManager {
public static void main(String[] args) {
Worker currentWorker = new Worker();
currentWorker.runTask(1);
}
}
Overriding the toString Method
Every class in Java inherits from the Object class. By overriding the toString() method, you can provide a custom string repreesntation of an object, which is automatically invoked when the object is printed.
DataViewer.java
package com.service.utils;
class Record {
String entryTitle = "SystemLog";
int entryId = 101;
@Override
public String toString() {
return "Record [ID=" + entryId + ", Title=" + entryTitle + "]";
}
}
public class DataViewer {
public static void main(String[] args) {
Record myRecord = new Record();
// Printing the object directly calls the overridden toString method
System.out.println(myRecord);
}
}