Declarations not separated from rest of code
begin ... end => {...}
if cond then ...else... => if (cond) ... else ...
while cond do ... => while (cond) ...
repeat .. until cond => do {...} while !cond;
for i := 10 to 20 do ... => for (int i = 10; i <= 20; i++)...
Semicolons used as line terminator, not separator.
interface NewInterface extends OldInterface { method specifications> }
public class NewClass extends SuperClass implements NewInterface { instance variable declarations constructor declarations and bodies method declarations and bodies }Extends and Implements clauses are optional (everything automatically inherits from Object).
See Employee example on-line.
Only declare method public if intended to be used by clients (external objects)
Notice can refer to instance variables within methods without passing as parameters (global to class). Can also refer to instance variables as components of this. E.g., this.top
Keyword this refers to object executing method
Notice HourlyEmployee and ExemptEmployee declared as subclasses using extends.
Employee myEmployee;then create via
myEmployee = new Employee(...);where Employee(...) is a constructor for Employee type.
If variable declared with a static type of, say Employee, but want to instantiate as HourlyEmployee, then write:
myEmployee = new HourlyEmployee(...);In general can always use object of a subclass in place of object of superclass.
Equality test (==) tests if identical references,
I.e., if fst, snd : Employee, and execute: fst = send, then change to fst.Name will change snd.Name.
Typically create a new object using a class constructor or use clone method inherited from Object (see pg 64 of text). Object also has equals method.
Can assign an object of subclass to variable of superclass (but not vice-versa).
Can also pass an object of subclass as parameter where expect object of superclass.
E.g.
public void DoSomething(Employee thisEmployee,... ); begin : System.out.println(thisEmployee.GetName() + " makes " + thisEmployee.GetWkPay()); : end;If pass in a parameter of class Employee, then print out 0.
If pass in a parameter of class HourlyEmployee, then print out 40 * HourlySalary.
If pass in a parameter of class ExemptEmployee, then print out yearlySalary / 52.
Uses dynamic method-lookup of message to find corresponding method of object.
E.g., if emp is type Employee, hEmp is type HourlyEmployee, then can write:
emp = hemp; hEmp = emp ; // Illegal assignment - won't compile! hEmp = (HourlyEmployee) emp; // example of downcast // Ok if emp is really HourlyEmployee, raises exception otherwise if (emp instanceof HourlyEmployee) then // Safer alternative - check before casting! hemp := (HourlyEmployee)emp; emp.setHourlyPay(6.25f) // illegal even though emp is really HourlyEmployee ((HourlyEmployee) emp ).setHourlyPay(6.25f) // OK since did cast first