發布者:vincent6 | 一月 15, 2008

instanceof test

package PracticalJava;

interface Employee {
  public int salary();
}
class Manager implements Employee {
  private static final int mgrSal = 40000;
  public int salary () {
  return mgrSal;
  }
}
class Programmer implements Employee {
  private static final int prgSal = 50000;
  private static final int prgBonus = 10000;
  public int salary() {
  return prgSal;
  }
  public int bonus () {
  return prgBonus;
  }
}

public class Payroll {

public int calcPayroll (Employee emp) {
  int money = emp.salary();
  if (emp instanceof Programmer)
  money += ((Programmer)emp).bonus(); //Calculate the bonus
  return money;
  }

public static void main(String[] args) {
  Payroll pr = new Payroll();
  Programmer prg = new Programmer();
  Manager mgr = new Manager();
  System.out.println("Payroll for Programmer is "+pr.calcPayroll(prg));
  System.out.println("Payroll for Manager is "+pr.calcPayroll(mgr));

}

}

這個寫法還有改善的機會,運用多型的方式評估到底適不適合用 instanceof.

發布者:vincent6 | 一月 14, 2008

Stack Test – Object reference question.

import java.util.EmptyStackException;

public class Stack {

    private Object[] elements;
    private int size = 0;
   
    public Stack(int initialCapacity) {
        this.elements = new Object[initialCapacity];
    }
   
    public void push(Object e) {
        ensureCapacity();
        elements[size++] = e;
    }
   
    public Object pop() {
        if (size == 0)
            throw new EmptyStackException();
       
        Object result = elements[--size];
        elements[size] = null;
        return result;
        //return elements[--size]; 此行寫法將無法 release object reference.
    }
   
    /**
     * Ensure space for at least one more element, roughly
     * doubling the capacity each time the array needs to grow.
     */
    private void ensureCapacity() {
        if (elements.length == size) {
            Object[] oldElements = elements;
            elements = new Object[2 * elements.length + 1];
            System.arraycopy(oldElements, 0, elements, 0, size);
        }
    }
   
    /**
     * @param args
     */
    public static void main(String[] args) {
        Stack stack = new Stack(10);
        stack.push(new Object());
        System.out.println(stack.pop());
        //System.out.println(stack.pop());
    }

}

發布者:vincent6 | 一月 14, 2008

第一個Blog! let’s blogging!!

Yes!!!

分類