- say you are implementing an employee database
- Employee' will be an object
- Employees start out w/ an employee number which is given but never changes
- default salary is $40,000 which can change or start different
- employees have names which are initially given but CAN change
- Need to be able to read:
- Name
- Employee Number
- Annual Salary
- Monthly Salary
- these are the 'accessors' for the program.
public class Employee {
//constructors
public Employee (String name, int enum, double salary)
public Employee (String name, int enum)
//methods: accessors
public String GetName()
public int GetEmNum()
public double GetAnnSalary()
public double GetMonSalary()
//methods: mutators
public void SetName(String Name)
public void SetSalary(double salary)
//fields
private String EmployeeName;
private int EmployeeNumber;
private double EmployeeSalary;
- after writing this on the board Andrew carried on w/ code he prepared before class
Utility Classes And The 'Static' Keyword
- a utility class is a special class w/ no fields that only provides methods that are useful to other objects.
- example: java.lang.math
Why Have Utilities?
- to organize useful methods in a matter similar to objects
- use methods w/o involking storage
example:
double x;
x.sqrt();
- the keyword 'static' is used to refer to methods that can be used independantly of objects
class myClass {
public static void mymethod(){}
}
myClass mc = new myClass();
//legal to say
mc.mymethod();
//also legal to say
myclass.mymethod(); //better practice
//legal to use even if no objects of type myClass exist
example 2
public class myutil{
public static int addint(int a, int b){
return a+b;
}
}
c= myutil.addint(3,4;
system.out.println(c);
//console
return: 7
- Can prevent the compiler from crashing an object relating to a utility class
- use a private constructor
private myutil(){}
// prevents someone trying to make a 'myutil' object
- now no outside class has the right to execute the constructor, so an object type util cannot be created.
No comments:
Post a Comment