Title: ObjectOriented Programming
1Object-Oriented Programming
Introduction
- What is Object Oriented Programming?
- Object oriented Programming languages (OOP for
short) include all the features of structured
programming and add more powerful ways to
organize algorithms and data structures. - There are three key features of OOP languages
- Encapsulation
- Inheritance
- Polymorphism
- All of them are tied to the notion of a class
2Classes and Objects
- A class defines a set of variables (data members
or data attributes) that can be associated with
the methods which act on an object with the
object itself. - An object is created through the instantiation of
a class. - You can look around you now and see many examples
of real-world objects your dog, your desk, your
television set, your bicycle. - These real-world objects share two
characteristics they all have state and they all
have behavior. For example, cars have state
(current gear, number of seats, four wheels,
etc.) and behavior (braking, accelerating,
slowing down, changing gears).
3Classes
- A class can be viewed as a blueprint of an
object. - It is the model or pattern from which objects are
created. - For example, the String class is used to define
String objects. - Each String object contains specific characters
(its state). - Each String object can perform services
(behaviors) such as toUpperCase.
4Classes
class TestStringClass public static void
main(String s) String s1 new
String("Programming") String s2 new
String("Java") String s3 new
String("ivet-ty") System.out.println(s1.toU
pperCase()) System.out.println(s2.toUpperCas
e()) System.out.println(s3.toUpperCase())
In this example, String is class. s1, s2 and s3
are the objects (or references to objects,
precisely speaking). Each of them has different
state but same behavior.
5Classes and Objects
String (class)
- The String class can be used to define as many
String objects as you like. - Its reusability is very high.
- The String class is provided for us by the Java
standard class library. - But we can also write our own classes that define
specific objects that we need
6Classes
- A class contains data declarations and method
declarations
int x, y char ch
Data declarations
Method declarations
7Example
- Let's define a very simple Employee class which
has one data member and two methods.
- class Employee
- int empnum // data member (instance
variable) - public int getNum() // method
- return empnum
-
- public void setNum(int newNum) // method
- empnum newNum
-
-
8Example
- Thus when we create a new object we say we are
instantiating the object. Each class exists only
once in a program, but there can be many
thousands of objects that are instances of that
class. - To instantiate an object in Java we use the new
operator. Here's how we'd create a new employee - Employee x new Employee()
- The instantiation can also be done in two lines
- Employee x
- x new Employee()
9Example
- The members of an object are accessed using the .
(dot) operator, as follows - Employee x new Employee()
- x.setNum(12651)
10Example
- We define a test driver class to test the
Employee class
- class Employee
- private int empnum
- public int getNum()
- return empnum
-
- public void setNum(int newNum)
- empnum newNum
-
-
- class TestEmployee
- public static void main(String args)
- Employee emp1 new Employee()
- Employee emp2 new Employee()
- emp1.setNum(12651)
- emp2.setNum(36595)
- System.out.println("num of emp1 "
emp1.getNum()) - System.out.println("num of emp2 "
emp2.getNum()) -
Sample Run gt java TestEmployee num of emp1
12651 num of emp2 36595
11- Note when you compile the file Employee.java, you
get two class files - Employee.class and TestEmployee.class.
- You can save the above program (two class
definitions) into one source file. - But if both of them are public, they must be
defined in separate files. - Every Java class must extend another class
- If class does not explicitly extend another class
- class implicitly extends Object
- So class Employee extends java.lang.Object
- is same as class Employee
12Encapsulation
- Encapsulation is used to hide unimportant
implementation details from other objects. - Thus, the implementation details can change at
any time without affecting other parts of the
program. - Benefits of Encapsulation
- Modularity -- each object can be written and
maintained independently of other objects. Also,
an object can be easily passed around in the
system. - Information hiding -- an object can maintain
private information and methods that can be
changed at any time without affecting the other
objects that depend on it
13A BAD Example
- The following example shows an incorrect use of
public data member.
- class PublicDataEmployee
- public int empnum
-
- class PrintEmployee1
- public static void main(String args)
- PublicDataEmployee emp new
PublicDataEmployee() - emp.empnum 12651
- System.out.println("num of emp "
emp.empnum) -
-
gt java PrintEmployee1 num of emp 12651
14A GOOD Example
- The following shows how to fix the problem in the
previous example.
- class PrivateDataEmployee
- private int empnum
- public int getNum()
- return empnum
-
- public void setNum(int newNum)
- empnum newNum
-
-
- class PrintEmployee2
- public static void main(String args)
- PrivateDataEmployee emp new
PrivateDataEmployee() - emp.setNum(12651)
- System.out.println("num of emp "
emp.getNum()) -
-
gt java PrintEmployee2 num of emp 12651
15Why is PrivateDataEmployee better?
- PublicDataEmployee is shorter than
PrivateDataEmployee. - Why do we say PrivateDataEmployee is better?
- Suppose the company wants to make the employee
number more meaningful by dividing the employee
number into two parts, deptID and staffID, and
the employee number is obtained by the formula
deptID1000 staffID. - e.g. If the IT Dept has department ID 13 and the
staff ID of Paul Leung is 228, then his employee
number is 13228.
16- Consider the class PublicDataEmployee, it needs
to be changed to
class PublicDataEmployee2 public int
deptID public int staffID class
PrintEmployee3 public static void
main(String args) PublicDataEmployee2
emp new PublicDataEmployee2() emp.empnum
12651 System.out.println("num of emp "
emp.empnum)
- PrintEmployee3 cannot be compiled anymore. You
have to change every occurrence of emp.empnum in
all programs that use PublicDataEmployee!!!!
17- The class PrivateDataEmployee can be modified to
meet the new requirement easily.
gtjava PrintEmployee4 num of emp 12651
class PrivateDataEmployee2 private int
deptID private int staffID public int
getNum() return deptID1000staffID
public void setNum(int newNum)
deptID newNum/1000 staffID
newNum1000 class PrintEmployee4
public static void main(String args)
PublicDataEmployee emp new PublicDataEmployee()
emp.setNum(12651)
System.out.println("num of emp "
emp.getNum())
18- We only need to change PrivateDataEmployee2 and
all other classes that depend on it (e.g.
PrintEmployee4) does not need to change. - The use of private data with set and get methods
can also protect the data from invalid
modification. - e.g. To prevent setting of an employee number to
a negative value, you can modify setNum as
public void setNum(int newNum) if (newNum lt
0) System.out.println("Invalid emp.
num.") else empnum newNum
19Controlling Access to Members
- Member access modifiers
- Control access to class instance variables and
methods - public
- Variables and methods accessible to other classes
- private
- Variables and methods not accessible to other
classes - Can be accessed via
- Accessor method (get method)
- Allow clients to read private data
- Mutator method (set method)
- Allow clients to modify private data
20class PrivateDataEmployee3 private int
empnum public int getNum() return
empnum public void setNum(int newNum)
empnum newNum class
PrintEmployee5 public static void
main(String args) PrivateDataEmployee3
emp new PrivateDataEmployee3()
emp.empnum 12651
gtjavac PrivateDataEmployee3.java PrivateDataEmploy
ee3.java15 empnum has private access in
PrivateDataEmployee3 emp.empnum 12651
1 error
21Method Control Flow
- The called method could be part of another class
or object
22Initializing Class Objects Constructors
- Class constructor
- Same name as class
- No return type or return statement
- Initializes instance variables of a class object
- Cannot be called directly
- Called when instantiating object of that class
- If no constructor is defined by the programmer, a
default "do-nothing" constructor is created for
you. - Java does not provide a default constructor if
the class define a constructor of its own.
23Constructor Example
- class Employee1
- private int empnum
- public Employee1(int newNum)
- empnum newNum // call setNum is better,
why? -
- public int getNum()
- return empnum
-
- public void setNum(int newNum)
- empnum newNum
-
-
- class PrintEmployee5
- public static void main(String args)
- Employee1 emp new Employee1(71623)
- System.out.println(emp.getNum())
gtjava PrintEmployee5 71623
24Using Overloaded Constructors
- Overloaded constructors
- Methods (in same class) may have same name
- Must have different parameter lists
- Examples in Java
- String
- JButton
- .......
25Time2.javaLines 16-19Default constructor has
no arguments Lines 23-26Overloaded constructor
has one int argument Lines 30-33Second
overloaded constructor has two int arguments
- 1 // Fig. 8.6 Time2.java
- 2 // Time2 class definition with overloaded
constructors. - 3
- 4
- 5 // Java core packages
- 6 import java.text.DecimalFormat
- 7
- 8 public class Time2
- 9 private int hour // 0 - 23
- 10 private int minute // 0 - 59
- 11 private int second // 0 - 59
- 12
- 13 // Time2 constructor initializes each
instance variable - 14 // to zero. Ensures that Time object
starts in a - 15 // consistent state.
- 16 public Time2()
- 17
- 18 setTime( 0, 0, 0 )
- 19
26Time2.javaLines 36-39Third overloaded
constructor has three int arguments Lines
42-45Fourth overloaded constructor has Time2
argument
- 35 // Time2 constructor hour, minute and
second supplied - 36 public Time2( int h, int m, int s )
- 37
- 38 setTime( h, m, s )
- 39
- 40
- 41 // Time2 constructor another Time2
object supplied - 42 public Time2( Time2 time )
- 43
- 44 setTime( time.hour, time.minute,
time.second ) - 45
- 46
- 47 // Set a new time value using universal
time. Perform - 48 // validity checks on data. Set invalid
values to zero. - 49 public void setTime( int h, int m, int s
) - 50
- 51 hour ( ( h gt 0 h lt 24 ) ? h 0
) - 52 minute ( ( m gt 0 m lt 60 ) ? m
0 ) - 53 second ( ( s gt 0 s lt 60 ) ? s
0 )
27Time2.java
- 70
- 71 return ( (hour 12 hour 0) ?
12 hour 12 ) - 72 "" twoDigits.format( minute )
- 73 "" twoDigits.format( second )
- 74 ( hour lt 12 ? " AM" " PM" )
- 75
- 76
- 77 // end class Time2
28TimeTest4.java Line 15Declare six references
to Time2 objects Lines 17-22Instantiate each
Time2 reference using a different constructor
- 1 // Fig. 8.7 TimeTest4.java
- 2 // Using overloaded constructors
- 3
- 4 // Java extension packages
- 5 import javax.swing.
- 6
- 7
- 8
- 9
- 10 public class TimeTest4
- 11
- 12 // test constructors of class Time2
- 13 public static void main( String args )
- 14
- 15 Time2 t1, t2, t3, t4, t5, t6
- 16
- 17 t1 new Time2() //
000000 - 18 t2 new Time2( 2 ) //
020000 - 19 t3 new Time2( 21, 34 ) //
213400
29TimeTest4.java
- 34 output "\nt3 hour and minute
specified " - 35 "second defaulted"
- 36 "\n " t3.toUniversalString()
- 37 "\n " t3.toString()
- 38
- 39 output "\nt4 hour, minute, and
second specified" - 40 "\n " t4.toUniversalString()
- 41 "\n " t4.toString()
- 42
- 43 output "\nt5 all invalid values
specified" - 44 "\n " t5.toUniversalString()
- 45 "\n " t5.toString()
- 46
- 47 output "\nt6 Time2 object t4
specified" - 48 "\n " t6.toUniversalString()
- 49 "\n " t6.toString()
- 50
- 51 JOptionPane.showMessageDialog( null,
output, - 52 "Demonstrating Overloaded
Constructors",
30TimeTest4.javaDifferent outputs, because each
Time2 reference was instantiated with a different
constructor
Different outputs, because each Time2 reference
was instantiated with a different constructor
31Final Instance Variables
- final keyword
- Indicates that variable is not modifiable
- Any attempt to modify final variable results in
error - Declares variable INCREMENT as a constant
- Enforces principle of least privilege
private final int INCREMENT 5
32Constants
- More often constants will be defined as public
and static - public - Other classes can read the value of the
constant - static - only one copy shared by all objects,
hence save memory (see next slide) - Example in Java - JOptionPane, String, Math, .....
33Static Class Members
- Most properties, like the balance in bank
account, are unique to the object, which should
be stored as instance variable (data member). - But some properties are shared among all objects
of a given class. For example, the interest rate
is a property shared by all saving accounts in
the same bank. - Such properties are called class member.
- Class members are defined using the keyword
static. So class members are also called static
members.
34Static Class Members
- static class variable
- Class-wide information
- All class objects share same data
- can be accessed via class name or an object
reference - static method
- can be accessed via class name or an object
reference - can access static members only (i.e. CANNOT read
non-static instance variables or call non-static
methods.)
35Static Class Members
- When should an instance variable be declared as
static? - data will be shared by all classes (e.g. Employee
Counter, Account Interest, constants) - it saves memory and is easy to maintain
- When should a method be declared as static?
- the method will be used as an utility, not
operates on an object (e.g. main, Math.sqrt,
Math.sin, .....)
36 - // TestStatic.java
- class Employee
- static int MaxNum 20000
- private int empNum
- public int getEmpNum()
- return empNum
-
- public void setEmpNum(int newNum)
- if (newNumltMaxNum newNum gt1)
- empNum newNum
-
-
- class TestStatic
- public static void main(String args)
- Employee emp1 new Employee()
- Employee emp2 new Employee()
- System.out.println("MaxNum of emp1 "
emp1.MaxNum)
gtjava TestStatic MaxNum of emp1 20000 MaxNum of
emp2 20000 MaxNum of emp2 99999
37Using the this Reference
- Is it possible to have parameter name same as
instance variable (data member)? YES! - class UseOfThis
- private int empID
- public int getEmpID()
- return empID
-
- public void setEmpID(int empID)
- System.out.println("Inside setEmpID ")
- System.out.println(" this.empID "
this.empID) - System.out.println(" empID " empID)
- this.empID empID
-
-
- class TestUseOfThis
- public static void main(String args)
- UseOfThis emp new UseOfThis()
gtjava TestUseOfThis Inside setEmpID
this.empID 0 empID 12651 num of emp 12651
38Using the this Reference
- Another use of the this reference is to allows a
method to return the object itself. - An example of using this as a reference to the
object itself is to be shown later (GUI
Event-Handling)
39Inheritance
- Object-oriented systems allow classes to be
defined in terms of other classes. - Classes can inherit variables and methods
(operations) from other classes. The inheriting
class can then add extra attributes and/or
methods of its own.
40Purpose of Inheritance
- Extend the functionality of an existing class.
- Share the commonality between two or more classes
.
41Example
- class BankAccount
- private double balance
- public double getBalance
- // other member functions
-
- class ChequeAccount extends BankAccount
- public void writeCheque (double amount)
- //...
-
- // other member functions
-
- In the above example, ChequeAccount inherits from
BankAccount. We can say that ChequeAccount is a
subclass (or derived class or child class)of
BankAccount and BankAccount is called a super
class (or base class or parent class).
42- Java does not support multiple inheritance. i.e.
A subclass cannot inherit from more than one
super classes.
X
class PT_Stduent extends Student, Worker
- Inheritance is between classes, NOT between
objects.
43(No Transcript)
44Software Engineering with Inheritance
- Inheritance
- Create class (subclass) from existing one
(superclass) - Subclass creation does not affect superclass
- New class inherits attributes and behaviors
- Software reuse
- Don't over use Inheritance!
- Inheritance
- Is a relationship
- A Manager is an Employee
- Composition
- Has a relationship
- A Manager has a Secretary
45Implicit Subclass-Object-to-Superclass-Object
Conversion
- Superclass reference and subclass reference
- Four ways to mix and match references and actual
objects - Refer to superclass object with superclass
reference - Refer to subclass object with subclass reference
- Refer to subclass object with superclass
reference - Can refer only to superclass members
- Refer to superclass object with subclass
reference - Syntax error!!
46 class Person // ... class Student extends
Person // ... class TestSubRef public
static void main(String s) Person parent
new Person() Student child new
Student() Person p Student c p
parent p child c parent c
child
gtjavac TestSubRef.java TestSubRef.java15
incompatible types found Person required
Student c parent 1 error
X
47Example
- Here is a program that uses a class VideoTape to
represent tapes available at a video tape rental
store. Inheritance is not used in this program
(so far).
class VideoTape String title // name of
the item int length // number of
minutes boolean avail // is the tape in the
store? public VideoTape( String ttl, int lngth
) title ttl length lngth avail
true public void show()
System.out.println( title ", " length
" min. available" avail
) class TapeStore public static void
main ( String args ) VideoTape item1
new VideoTape("Jaws", 120 ) item1.show()
48- The output is Jaws, 120 min. available true
- The VideoTape class has basic information in it,
and would be OK for documentaries and
instructional tapes. - But movies need more information. Let us make a
class that is similar to VideoTape, but has the
name of the director and a rating.
class Movie extends VideoTape String
director // name of the director String
rating // G, PG, R, or X //
constructor public Movie( String ttl, int
lngth, String dir, String rtng )
super(ttl, lngth) // use the super
class' constuctor director dir rating
rtng // initialize what's new to Movie
49- The statement super(ttl, lngth) calls the super
class' constructor to initialize some of the
data. - The class Movie is a subclass of VideoTape. An
object of type Movie has the following members in
it
50- You don't have to use super the following would
also work as a constructor for Movie
// constructor public Movie( String ttl, int
lngth, String dir, String rtng ) title
ttl length lngth avail true director
dir rating rtng
- You should not write the same code more than
once. You might make a mistake the second time
(for example forgetting to initialize the member
avail.)
51- Here is an example program that makes use of the
two classes VideoTape and Movie
class TapeStore2 public static void main (
String args ) VideoTape item1 new
VideoTape("Microcosmos", 90 ) Movie
item2 new Movie("Jaws", 120, "Spielberg", "PG"
) item1.show() item2.show()
Output Microcosmos, 90 min. availabletrue Jaws,
120 min. availabletrue
52Method Overriding
- We need a new show() method in the class Movie
// added to class Movie public void show()
System.out.println(title ", " length
" min. available" avail)
System.out.println( "dir " director " "
rating )
- Even though the parent has a show() method the
new definition of show() in the child class will
override the parent's version. - A child overrides a method from its parent by
defining a replacement method with the same
signature.
Output Microcosmos, 90 min. availabletrue Jaws,
120 min. availabletrue dir Spielberg PG
53Using super in a Child's Method
- Sometimes (as in the example) you want a child
class to have its own method, but that method
includes everything the parent's method does.
Consider VideoTape's show() method - Here is Movie's method
public void show() System.out.println( title
", " length " min.
available" avail )
public void show() System.out.println( title
", " length " min.
available" avail ) System.out.println(
"dir " director " " rating )
- We wrote the same code twice!!
54Using super in a Child's Method
- You can use the super reference in this
situation. Movie's method would better be written
using super
public void show() super.show()
System.out.println( "dir " director " "
rating )
55Example on Overriding
class Base public int f() return 10
public int g() return 22 class
Derived extends Base public int f()
return 999 public class Override
public static void main(String args) Base
b new Base() Derived d new Derived()
System.out.println("b.f() " b.f())
System.out.println("b.g() " b.g())
System.out.println("d.f() " d.f())
System.out.println("d.g() " d.g())
Output gt java Override b.f() 10 b.g()
22 d.f() 999 d.g() 22
56protected Members
- Subclass objects cannot access private members of
superclass. - You can declare class members as protected
- protected access members
- Between public and private in protection
- Can be thought as accessible in package
subclasses - Accessed only by
- The methods defined in the class
- Subclass methods
- Methods of classes in same package
class VideoTape protected String title
// name of the item protected int length
// number of minutes protected boolean avail
// is the tape in the store? //
........................
57default super() call
class SuperClass SuperClass(int i)
System.out.println("i " i) class
SubClass extends SuperClass SubClass(int i)
System.out.println("Sub is called")
class TestSuperCall public static void
main(String s) SubClass sub new
SubClass(1)
58default super() call
class SuperClass SuperClass(int i)
System.out.println("i " i) class
SubClass extends SuperClass SubClass(int i)
super() // added by Java compiler
automatically. System.out.println("Sub is
called") class TestSuperCall public
static void main(String s) SubClass sub
new SubClass(1)
No default constructor!
59default super() call
class SuperClass SuperClass(int i)
System.out.println("i " i) class
SubClass extends SuperClass SubClass(int i)
super(i) // call super class constructor
explicitly System.out.println("Sub is
called")
class SuperClass SuperClass()
System.out.println("SuperClass's constructor is
called") SuperClass(int i)
System.out.println("i " i)
60Abstract Class
- There are some situations in which it is useful
to define base classes that are never
instantiated. - Such classes are called abstract classes.
- For instance, we could have an abstract
superclass shape and derive concrete classes
(non-abstract classes) such as square, circle,
triangle etc. - We do not know how to implement the area() method
of the Shape class - leave it empty and let
subclasses to define it (abstract method).
61Abstract Methods
- A method declared as abstract is NOT allowed to
contain a body. - public abstract void f()
- To force the subclasses to define the method.
- A class must be declared as abstract if it
contains one or more abstract methods.
62Abstract Class Syntax
- A class is made abstract by declaring it with the
keyword abstract.
abstract public class Shape String name
abstract public double area() public String
name() return name //other stuff
- An abstract class cannot be instantiated.
63Can't Instantiate an Abstract Class
- The following example tries to instantiate an
abstract class.
abstract class Shape String name abstract
public double area() public String name()
return name //other stuff class TestShape
public static void main(String args)
Shape s new Shape()
gtjavac TestShape.java TestShape.java10 Shape is
abstract cannot be instantiated Shape s
new Shape() 1 error
64Abstract Method gt Abstract Class
- if a class contains even one abstract method,
then the class itself has to be declared to be
abstract.
class Shape String name abstract public
double area() public String name() return
name //other stuff class TestShape
public static void main(String args)
Shape s new Shape()
gtjavac TestShape2.java TestShape2.java1 Shape
should be declared abstract it does not define
area() in Shape class Shape 1 error
65Example
- The class inherits from Shape MUST implement
(provide a method body) area().
abstract class Shape String name abstract
public double area() public String name()
return name //other stuff class Square
extends Shape double length public
Square(double length) this.length length
public double area() return lengthlength
class TestShape3 public static void
main(String args) Square s new
Square(12.5) System.out.println("The area of
square s is " s.area())
Output The area of square s is 156.25
66Introduction to Polymorphism
- Polymorphism
- Polymorphism means "having many forms."
- In Java, it means that a single variable might be
used with several different types of related
objects at different times in a program. - Recall that a superclass reference can refer to
subclass objects. - When the variable is used with "dot notation"
variable.method() to invoke a method, exactly
which method is run depends on the object that
the variable currently refers to.
67Example
- Consider the previous example, suppose we want to
add a new class Circle that inherits from Shape.
// Shape and Square are same as before class
Circle extends Shape double radius public
Circle(double radius) this.radius radius
public double area() return
Math.PIradiusradius class TestShape4
public static void main(String args)
Shape s new Square(12.5)
System.out.println("The area of s is "
s.area()) s new Circle(5)
System.out.println("The area of s is "
s.area())
Output The area of s is 156.25 The area of s is
78.539816339744
68Advantages of using Polymorphism
- Polymorphism
- Reduce amount of work in distinguishing and
handling object types - Old approach - Determine the object type and then
uses a nested if-else statement to execute the
appropriate statements (difficult and easy to
make mistake) - Helps build extensible systems
- Program can be written to process objects of
types that may not exist when the program is
under development. - Can add classes to systems easily
69Case Study A Payroll System Using Polymorphism
- Example
- Abstract superclass Employee
- Method earnings applies to all employees
- Persons earnings dependent on type of Employee
- Concrete Employee subclasses declared final
- Boss
- CommissionWorker
- HourlyWorker
70- Note that all classes are in TestEmployee.java.
abstract class Employee private String
firstName private String lastName //
Constructor public Employee( String first,
String last ) firstName first
lastName last // Return a copy of the
first name public String getFirstName()
return firstName // Return a copy of the
last name public String getLastName()
return lastName // Abstract method that
must be implemented for each // derived class
of Employee from which objects // are
instantiated. abstract double earnings()
71// Definition of class HourlyWorker final class
HourlyWorker extends Employee private double
wage // wage per hour private double hours
// hours worked for week // Constructor for
class HourlyWorker public HourlyWorker( String
first, String last,
double w, double h ) super( first, last
) // call base-class constructor
setWage( w ) setHours( h ) //
Set the wage public void setWage( double w )
wage ( w gt 0 ? w 0 ) // Set the hours
worked public void setHours( double h )
hours ( h gt 0 h lt 168 ? h 0 ) //
Get the HourlyWorker's pay public double
earnings() return wage hours public
String toString() return "Hourly worker
" getFirstName() ' '
getLastName()
72final class Boss extends Employee private
double weeklySalary // Constructor for class
Boss public Boss( String first, String last,
double s) super( first, last ) //
call base-class constructor
setWeeklySalary( s ) // Set the Boss's
salary public void setWeeklySalary( double s
) weeklySalary ( s gt 0 ? s 0 )
// Get the Boss's pay public double earnings()
return weeklySalary // Print the Boss's
name public String toString()
return "Boss " getFirstName() ' '
getLastName()
73// CommissionWorker class derived from
Employee final class CommissionWorker extends
Employee private double salary // base
salary per week private double commission //
amount per item sold private int quantity
// total items sold for week // Constructor
for class CommissionWorker public
CommissionWorker( String first, String last,
double s, double c, int q)
super( first, last ) // call base-class
constructor setSalary( s )
setCommission( c ) setQuantity( q )
// Set CommissionWorker's weekly base
salary public void setSalary( double s )
salary ( s gt 0 ? s 0 ) // Set
CommissionWorker's commission public void
setCommission(double c) commission ( cgt0 ? c
0 ) // Set CommissionWorker's quantity
sold public void setQuantity( int q )
quantity ( q gt 0 ? q 0 ) // Determine
CommissionWorker's earnings public double
earnings() return salary commission
quantity // Print the CommissionWorker's
name public String toString() return
"Commission worker "getFirstName()'
'getLastName()
74// CommissionWorker class derived from
Employee final class CommissionWorker extends
Employee private double salary // base
salary per week private double commission //
amount per item sold private int quantity
// total items sold for week // Constructor
for class CommissionWorker public
CommissionWorker( String first, String last,
double s, double c, int q)
super( first, last ) // call base-class
constructor setSalary( s )
setCommission( c ) setQuantity( q )
// Set CommissionWorker's weekly base
salary public void setSalary( double s )
salary ( s gt 0 ? s 0 ) // Set
CommissionWorker's commission public void
setCommission(double c) commission ( cgt0 ? c
0 ) // Set CommissionWorker's quantity
sold public void setQuantity( int q )
quantity ( q gt 0 ? q 0 ) // Determine
CommissionWorker's earnings public double
earnings() return salary commission
quantity // Print the CommissionWorker's
name public String toString() return
"Commission worker "getFirstName()'
'getLastName()
75// Driver for Employee hierarchy class
TestEmployee1 public static void
main(String args) Employee emp //
base-class reference emp new Boss( "John",
"Smith", 800.00 ) System.out.println(emp.toSt
ring() " earned "
emp.earnings() ) emp new
CommissionWorker( "Sue", "Jones", 400.0, 3.0,
150) System.out.println(emp.toString() "
earned "
emp.earnings() ) emp new HourlyWorker(
"Karen", "Price", 13.75, 40 )
System.out.println(emp.toString() " earned "
emp.earnings() )
Output Boss John Smith earned 800.0 Commission
worker Sue Jones earned 850.0 Hourly worker
Karen Price earned 550.0
76Example (Continued)
- The above test program can be implemented by
using an Employee array.
class TestEmployee2 public static void
main(String args) Employee emp new
Employee3 // base-class reference emp0
new Boss( "John", "Smith", 800.00 ) emp1
new CommissionWorker( "Sue", "Jones", 400.0,
3.0, 150) emp2 new HourlyWorker(
"Karen", "Price", 13.75, 40 ) for (int i0
ilt emp.length i) System.out.println(empi
" earned "
empi.earnings() )
77Example - Add a New Worker
- Suppose we have to add a new worker of a new
PieceWorker class.
final class PieceWorker extends Employee
private double wagePerPiece // wage per piece
output private int quantity // output
for week // constructor for class
PieceWorker public PieceWorker(String first,
String last, double wage, int num) super(
first, last ) // call superclass constructor
setWage( wage ) setQuantity( num )
// set PieceWorker's wage public void
setWage(double wage) wagePerPiece(wagegt0?wage0
) // set number of items output public
void setQuantity( int numberOfItems )
quantity ( numberOfItems gt 0 ? numberOfItems
0 ) // determine PieceWorker's
earnings public double earnings() return
quantity wagePerPiece public String
toString() return "Piece worker "
getFirstName() ' ' getLastName() //
end class PieceWorker
78- Let's how easy we can modify the main program.
// Driver for Employee hierarchy class
TestEmployee3 public static void
main(String args) Employee emp new
Employee4 // base-class reference emp0
new Boss( "John", "Smith", 800.00 ) emp1
new CommissionWorker( "Sue", "Jones", 400.0,
3.0, 150) emp2 new HourlyWorker(
"Karen", "Price", 13.75, 40 ) emp3 new
PieceWorker( "Maggie", "Jackson", 5.5, 200 )
for (int i0 ilt emp.length i)
System.out.println(empi " earned "
empi.earnings() )
Output gtjava TestEmployee3 Boss John Smith
earned 800.0 Commission worker Sue Jones earned
850.0 Hourly worker Karen Price earned
550.0 Piece worker Maggie Jackson earned 1100.0