Java
Beginner
1 min read
Class Design: Constructors, Fields, and Getters/Setters
Example
public class Employee {
// Class-level: tracks total instance count
private static int instanceCount = 0;
// Instance fields
private final int id; // assigned at construction, never changes
private String name;
private String department;
private double salary;
// Primary constructor
public Employee(String name, String department, double salary) {
if (salary < 0) throw new IllegalArgumentException("Salary cannot be negative");
this.id = ++instanceCount;
this.name = name;
this.department = department;
this.salary = salary;
}
// Delegating constructor (calls primary constructor)
public Employee(String name, String department) {
this(name, department, 0.0); // new hire with no salary yet
}
// Static factory method (named constructor)
public static Employee intern(String name) {
return new Employee(name, "Internship", 15.0);
}
// Getters
public int getId() { return id; }
public String getName() { return name; }
public String getDepartment() { return department; }
public double getSalary() { return salary; }
// Setters with validation
public void setName(String name) {
if (name == null || name.isBlank()) throw new IllegalArgumentException("Name required");
this.name = name;
}
public void setSalary(double salary) {
if (salary < 0) throw new IllegalArgumentException("Salary cannot be negative");
this.salary = salary;
}
// Static getter for class-level field
public static int getInstanceCount() { return instanceCount; }
@Override public String toString() {
return String.format("Employee{id=%d, name='%s', dept='%s', salary=%.2f}",
id, name, department, salary);
}
public static void main(String[] args) {
Employee e1 = new Employee("Alice", "Engineering", 90_000);
Employee e2 = new Employee("Bob", "Marketing");
Employee e3 = Employee.intern("Carol");
System.out.println(e1);
System.out.println(e2);
System.out.println(e3);
System.out.println("Total employees created: " + Employee.getInstanceCount());
e2.setSalary(65_000);
System.out.println("After salary update: " + e2);
}
}