You can use enumerations for the same purpose, which restricts the use of only the specified values. Declare a Department listing as follows
public enum Department { Accounting, Marketting, Human_Resources, Information_Systems }
Employee class can now be
public class Employee { String name; int age; Department department; Employee(String name, int age, Department department) { this.name = name; this.age = age; this.department = department; } int getAge() { return age; } }
and when creating an employee you can use
Employee employee = new Employee("Prasad", 47, Department.Information_Systems);
EDIT proposed by Adrian Shum and of course because it is a great offer.
- Enumerations are constants, so it is useful to declare it in capital letters in accordance with java conventions.
- But we donβt want the representation of capital from enums displayed, so that we can create enum constructors and pass readable information to it.
We modify enum to include the toString() method and constructor , which takes a string argument.
public enum Department { ACCOUNTING("Accounting"), MARKETTING("Marketting"), HUMAN_RESOURCES( "Human Resources"), INFORMATION_SYSTEMS("Information Systems"); private String deptName; Department(String deptName) { this.deptName = deptName; } @Override public String toString() { return this.deptName; } }
So, when we create an Employee object as follows and use it,
Employee employee = new Employee("Prasad Kharkar", 47, Department.INFORMATION_SYSTEMS); System.out.println(employee.getDepartment());
We get a readable string representation as Information Systems , because it is returned by the toString() method, which is implicitly called the System.out.println() operator. Read a good tutorial on Enumerations
Prasad Kharkar Jul 12 '13 at 3:23 2013-07-12 03:23
source share