Ch7 case studies

Document Sample
Ch7 case studies Powered By Docstoc
					Implement a superclass Person. Inherit two classes from Person, namely Student and Lecturer. A person
has a name and a year of birth. A student has a subject, and a lecturer a salary. Write the class
definitions, the constructors and the methods toString for all classes. Supply a test program that tests
these classes and methods.


Person.java
/**
   A person is represented by the name and a birth year
*/
public class Person
{
   /**
       Construct a Person object
       @param n the name of the person
       @param byear the birth year
   */
   public Person(String n, int byear)
   {
       name = n;
       birthYear = byear;
   }

      /**
            Print the string represention of the object
            @return a string representation of the object
      */
      public String toString()
      {
         return "Person[name=" + name + ",birthYear=" + birthYear + "]";
      }

      private String name;
      private int birthYear;
}

Lecturer.java
/**
   A lecturer is represented by a name, a birth year, and a salary
*/
public class Lecturer extends Person
{
   /**
       Construct a Lecturer object
       @param n the name of the lecturer
       @param byear the birth year
       @param s the salary
   */
   public Lecturer(String n, int byear, double s)
   {
       super(n, byear);
       salary = s;
   }

      /**
            Print the string representation of the object
            @return a string representation of the object
      */
      public String toString()
      {
         return "Employee[super=" + super.toString() + ",salary=" + salary + "]";
      }

      private double salary;
}

Student.java
/**
   A student is represented by the name, birth year, and subject
*/
public class Student extends Person
{
   /**
       Construct a Student object
       @param n the name of the student
       @param byear the birth year
       @param s the subject
   */
   public Student(String n, int byear, String s)
   {
       super(n, byear);
       subject = s;
   }

      /**
            Print the string represention of the object
            @return a string representation of the object
      */
      public String toString()
      {
         return "Student[super=" + super.toString() + ",subject=" + subject + "]";
      }

      private String subject;
}



Test.java

/**
   This class tests the Person, Student, and Lecturer classes
*/
public class test
{
   public static void main(String[] args)
   {
      Person p = new Person("Perry", 1959);
      Student s = new Student("Sylvia", 1979, "Computer Science");
      Employee e = new Employee("Edgar", 1969, 30000);
      System.out.println(p);
      System.out.println(s);
      System.out.println(e);
   }
}
 Implement the subclass Square that extends the Rectangle class, where the constructor takes the centre of
the square and its side length. Call the setLocation and setSize methods of the square (documentation in
Java Swing). Supply a method getArea that computes and returns the area of the square. Use a simple
test program.

Square.java
import java.awt.Rectangle;

//    A square is represented by the sides and the area

public class Square extends Rectangle
{
   /**
       Constructs a Square object
       @param the x coordinate
       @param the y coordinate
       @param the side length w
   */
   public Square(int x, int y, int w)
   {
       setLocation(x - w / 2, y - w / 2);
       setSize(w, w);
   }

     /**
           Computes the area of the square
           @return area of the square
     */
     public double getArea()
     {
        return getWidth() * getWidth();
     }
}

TestSquare.java
import javax.swing.JOptionPane;

//    This class tests the Square class

public class TestSquare
{
   public static void main(String[] args)
   {
      String input = JOptionPane.showInputDialog("x:");
      int x = Integer.parseInt(input);

           input = JOptionPane.showInputDialog("y:");
           int y = Integer.parseInt(input);

           input = JOptionPane.showInputDialog("side:");
           int s = Integer.parseInt(input);

           Square sq = new Square(x, y, s);
           System.out.println(sq.toString());
           System.out.println("Area = " + sq.getArea());

           System.exit(0);
     }
}
Make a class Employee with a name and salary. Make a class Manager inherit from employee.
Add an instance field department, of type String. Supply a method toString that prints the
manager's name, department and salary. Supply appropriate toString methods for all classes.
Supply a test program that tests these classes and methods.

Employee.java
/**
   An employee with salary
*/
public class Employee
{
   /**
       Construct an Employee object
       @param n the name of the employee
       @param s the salary of the employee
   */
   public Employee(String n, double s)
   {
       name = n;
       salary = s;
   }

      /**
            Print the string represention of the object
            @return a string representation of the object
      */
      public String toString()
      {
         return "Employee[name=" + name + ",salary=" + salary + "]";
      }

      private String name;
      private double salary;
}

Manager.java
/**
   A manager with salary working for a certain department
*/
public class Manager extends Employee
{
   /**
       Construct a Manager object
       @param n the name of the manager
       @param s the salary of the manager
       @param d the department where the manager works
   */
   public Manager(String n, double s, String d)
   {
       super(n, s);
       department = d;
   }

      /**
            Print the string represention of the object
            @return a string representation of the object
      */
      public String toString()
      {
         return "Manager[super=" + super.toString() + ",department=" +
               department + "]";
      }

      private String department;
}

Executive.java
/**
   An executive with a salary working for a certain department
*/
public class Executive extends Manager
{
   public Executive(String n, double s, String d)
   {
      super(n, s, d);
   }

      /**
            Print the string represention of the object
            @return a string representation of the object
      */
      public String toString()
      {
         return "Executive[super=" + super.toString() + "]";
      }
}

TestEmplyee.java
/**
      This program tests the Employee class and
      their subclasses.
*/
public class TestEmployee
{
   public static void main(String[] args)
   {
      Employee e = new Employee("Edgar", 65000);
      Manager m = new Manager("Mary", 85000, "Engineering");
      Executive v = new Executive("Veronica", 105000, "Engineering");
      System.out.println(e);
      System.out.println(m);
      System.out.println(v);
   }
}
(a)   Define a class Item and two subclasses Book and Periodical that might be included in
           a very simple program for keeping records of items in a library. A Book will have a
           title, an author and an ISBN number, all of which will be of type String. A
           Periodical will have a title which is a string, and a count of how many times a year
           the periodical is published.

            Include in the class Book a constructor Book(t,a,i) which will create a new Book
            object with title t, author a, and ISBN number i. Define a similar constructor
            Periodical(t,n) for the Periodical class. Also define for both classes an
            instance method display() which will display on the screen all the details of a book
            or periodical.

            For example, given your class definitions, it should be possible to execute the
            following statements.

                  Item it = new Book("Java made easy",
                                     "George Boole ",
                                     "1897851022");
                  it.display();


      (b)   What does it mean to say one class extends another class? What is dynamic binding.
            Give an example of both these things using the classes defined in part (a) of this
            question.


(a)   public abstract class Item

      { public abstract void display();
      }

      public class Book extends Item

      {     private String title;
            private String author;
            private String isbn;

            public void display()
            { System.out.println("Book title: " + title);
               System.out.println("Author: " + author);
               System.out.println("ISBN number: " + isbn);
            }

            public Book(String t, String a, String i)
            { title = t;
               author = a;
               isbn = i;
            }
      }

      public class Periodical extends Item
      {   private String title;
          private int howOften;

          public void display()
          { System.out.println
                ("Periodical title: " + title);
             System.out.println
                ("Number of issues per year: " + howOften);
          }

          public Periodical(String t, int n)
          { title = t;
             howOften = n;
          }
      }

      Note. There are other ways of defining these classes. For example, it is possible to place the
      title field in the Item class. Then a display method can be added to Item for
      displaying the title. Alternatively, the display methods in Book and Periodical can
      deal with displaying this field, but in that case there must be some way for them to access it.
      It can be declared to be protected, or a getTitle method could be added to Item.


(b)   If a class B extends a class A, objects of type B will have all the fields and methods that
      objects of type A have. In addition they will have the fields and methods specified in the
      definition of class B. In part (a) of the question, the classes Book and Periodical extend
      the class Item.

      Suppose class A has one or more subclasses. Then program code that apparently refers to
      objects of type A can be used to process objects belong to A’s subclasses. Java will wait
      until the code is executing before deciding which types of objects are being processed, and
      will then call the appropriate methods. This feature is called dynamic binding. For example,
      when the statement it.display() is executed, Java will check the object referred to by
      it and will call the appropriate display method, depending on whether it refers to a
      Book or a Periodical.
Write an abstract superclass worker and subclasses HourlyWorker and SalariedWorker. Every
worker has a name and salary rate. Write a method computPay(int, hours) that computes the pay
for every worker. An hourly worker gets a basic pay rate up to 40 hours and time and a half for
hours in excess of 40. A salaried worker has a basic pay rate of 40 hours, irrespect of the hours
worked. Supply a test program that uses polymorphism to test these classes and methods.

Worker.java
/**
   A worker gets paid at a current rate
*/
public abstract class Worker
{
   /**
       Construct a Worker object
       @param n the name of the work
       @param r the pay rate
   */
   public Worker(String n, double r)
   {
       name = n;
       rate = r;
   }

      /**
            Get the rate of the pay
            @return the rate
      */
      public double getRate()
      {
         return rate;
      }

      /**
            Abstract method to compute the pay
            @param hours the hours worked
      */
      public abstract double computePay(int hours);

      private String name;
      private double rate;
}

HourlyWorker.java
/**
   A worker who gets paid by the hour
*/
public class HourlyWorker extends Worker
{
   /**
       Construct a HourlyWorker object
       @param n the name of the worker
       @param r the pay rate
   */
   public HourlyWorker(String n, double r)
   {
       super(n, r);
   }

      /**
            Calculate the pay rate
            @param the hours worked
         @return the amount paid to worker
      */
      public double computePay(int hours)
      {
         double pay = getRate() * hours;
         if (hours > 40)
         {
            pay += getRate() * (hours - 40) / 2;
         }
         return pay;
      }
}

SalariedWorker.java
/**
   A worker who gets paid with a salary
*/
public class SalariedWorker extends Worker
{
   /**
       Construct a SalariedWorker object
       @param n the name of the worker
       @param r the pay rate
   */
   public SalariedWorker(String n, double r)
   {
       super(n, r);
   }

      /**
            Calculate the pay rate
            @param hours the hours worked
            @return pay the amount paid to worker
      */
      public double computePay(int hours)
      {
         return getRate() * 40;
      }
}

TestWorker.java
/**
   This class tests class Worker and its subclasses
*/
public class TestWorker
{
   public static void main(String[] args)
   {
      SalariedWorker s = new SalariedWorker("Sally", 40);
      HourlyWorker h = new HourlyWorker("Harry", 40);
      System.out.println(computePay(s, 30));
      System.out.println(computePay(h, 30));
      System.out.println(computePay(s, 50));
      System.out.println(computePay(h, 50));
   }

      public static double computePay(Worker w, int hours)
      {
         return w.computePay(hours);
      }
The following notes are taken from the texts:
Software Development with Oberon-2 —A Modular Approach. Claire Willis, 2000, Alpha Books.
Abstraction and Specification with Modula-2, Claire Willis & Derek Paddon, 1992, Pitman.

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:21
posted:6/24/2012
language:
pages:10