lec34

53
CS 101 Programming and Problem Solving Spring 2015 MWF 2:10 pm – 3:00 pm Stevenson Center 5326

Transcript of lec34

CS 101Programming and Problem Solving

Spring 2015MWF 2:10 pm – 3:00 pmStevenson Center 5326

Announcements

• Assignment 15 due Monday (04/20) at 11:59 pm• Late submissions will not be accepted

• Questions???

Law Firm Employee Analogy• Common rules: hours, vacation, benefits, regulations ...

• All employees attend a common orientation to learn general company rules

• Each employee receives a 20-page manual of common rules

• Each subdivision also has specific rules:• Employee receives a smaller (1-3 page) manual of these rules• Smaller manual adds some new rules and also changes some

rules from the large manual

Copyright © 2010

Separating Behavior

• Why not just have a 22 page Lawyer manual, a 21-page Secretary manual, a 23-page Marketer manual, etc.?

• Some advantages of the separate manuals:• Maintenance: Only one update if a common rule

changes• Locality: Quick discovery of all rules specific to

lawyers

• Some key ideas from this example:• General rules are useful (the 20-page manual)• Specific rules that may override general ones are also

usefulCopyright © 2010

Is-a Relationships, Hierarchies

• is-a relationship: A hierarchical connection where one category can be treated as a specialized version of another• Every marketer is an employee• Every legal secretary is a secretary

• Inheritance hierarchy: A set of classes connected by is-a relationships that can share common code

Copyright © 2010

Employee Regulations• Consider the following employee regulations:

• Employees work 40 hours / week• Employees make $40,000 per year, except legal

secretaries who make $5,000 extra per year ($45,000 total), and marketers who make $10,000 extra per year ($50,000 total)

• Employees have 2 weeks of paid vacation leave per year, except lawyers who get an extra week (a total of 3)

• Employees should use a yellow form to apply for leave, except for lawyers who use a pink form

• Each type of employee has some unique behavior:• Lawyers know how to sue• Marketers know how to advertise• Secretaries know how to take dictation• Legal secretaries know how to prepare legal documents

Copyright © 2010

An Employee Class// A class to represent employees in general (20-page manual).public class Employee {

public int getHours() {return 40; // works 40 hours / week

}public double getSalary() {

return 40000.0; // $40,000.00 / year}public int getVacationDays() {

return 10; // 2 weeks' paid vacation}public String getVacationForm() {

return "yellow"; // use the yellow form}

}

• Exercise: Implement class Secretary, based on the previous employee regulations (Secretaries can take dictation)

Copyright © 2010

Redundant Secretary Class// A redundant class to represent secretaries.public class Secretary {

public int getHours() {return 40; // works 40 hours / week

}public double getSalary() {

return 40000.0; // $40,000.00 / year}public int getVacationDays() {

return 10; // 2 weeks' paid vacation}public String getVacationForm() {

return "yellow"; // use the yellow form}public void takeDictation(String text) {

System.out.println("Taking dictation of text: " + text);}

}

Copyright © 2010

Desire for Code-sharing• takeDictation is the only unique behavior in Secretary

• We'd like to be able to say:// A class to represent secretaries.public class Secretary {

copy all the contents from the Employee class;

public void takeDictation(String text) {System.out.println("Taking dictation of text: “

+ text);}

}

Copyright © 2010

Inheritance

• Inheritance: A way to form new classes based on existing classes, taking on their attributes/behavior• A way to group related classes• A way to share code between two or more classes

• One class can extend another, absorbing its data/behavior• Superclass: The parent/base class that is being

extended• Subclass: The child/derived class that extends the

superclass and inherits its behavior• Subclass gets a copy of every field and method from

superclassCopyright © 2010

Inheritance Syntaxpublic class name extends superclass {

• Example:public class Secretary extends Employee {

...}

• By extending Employee, each Secretary object now:• Receives a getHours, getSalary, getVacationDays, and getVacationForm method automatically

• Can be treated as an Employee by client code (seen later)

Copyright © 2010

Improved Secretary Code// A class to represent secretaries.public class Secretary extends Employee {

public void takeDictation(String text) {System.out.println("Taking dictation of text: "

+ text);}

}

• Now we only write the parts unique to each type• Secretary inherits getHours, getSalary, getVacationDays, and getVacationFormmethods from Employee

• Secretary adds the takeDictation method

Copyright © 2010

Implementing Lawyer

• Consider the following lawyer regulations:• Lawyers get an extra week of paid vacation (a total of 3)• Lawyers use a pink form when applying for vacation

leave• Lawyers have some unique behavior: they know how to

sue

• Problem: We want lawyers to inherit most behavior from employee, but we want to replace parts with new behavior

Copyright © 2010

Overriding Methods

• Override: To write a new version of a method in a subclass that replaces the superclass's version• No special syntax required to override a superclass

method. Just write a new version of it in the subclasspublic class Lawyer extends Employee {

// overrides getVacationForm method in Employee classpublic String getVacationForm() {

return "pink";}...

}

• Exercise: Complete the Lawyer class• (3 weeks vacation, pink vacation form, can sue)

Copyright © 2010

Lawyer Class// A class to represent lawyers.public class Lawyer extends Employee {

// overrides getVacationForm from Employee classpublic String getVacationForm() {

return "pink";}

// overrides getVacationDays from Employee classpublic int getVacationDays() {

return 15; // 3 weeks vacation}

public void sue() {System.out.println("I'll see you in court!");

}

}

• Exercise: Complete the Marketer class. Marketers make $10,000 extra ($50,000 total) and know how to advertise

Copyright © 2010

Marketer Class// A class to represent marketers.public class Marketer extends Employee {

public void advertise() {System.out.println("Act now while supplies last!");

}

public double getSalary() {return 50000.0; // $50,000.00 / year

}}

Copyright © 2010

Levels of Inheritance

• Multiple levels of inheritance in a hierarchy are allowed

• Example:• A legal secretary is the same as a regular secretary

but makes more money ($45,000) and can file legal briefs

public class LegalSecretary extends Secretary {...}

• Exercise: Complete the LegalSecretary class

Copyright © 2010

A LegalSecretary Class// A class to represent legal secretaries.public class LegalSecretary extends Secretary {

public void fileLegalBriefs() {System.out.println("I could file all day!");

}

public double getSalary() {return 45000.0; // $45,000.00 / year

}}

• A LegalSecretary can do all things a Secretary can do, but• Can also file legal briefs (new behavior)• Gets paid more (changed behavior) – this is overriding

Copyright © 2010

Overriding Method Definitions

• When overriding a method, you can change the method definition to anything you wish, but you cannot change the method’s heading or the method’s return type

Copyright © 2010

Overriding vs. Overloading

• When you override a method, the new method definition in the derived class has the same name and the same number & types of parameters as the method definition in the base class

• When the name is the same, but the number or types of the parameters differs, whether in the base class or in the derived class, the method is overloaded in the derived class

Copyright © 2010

Overriding vs. Overloading

Example: if we hadpublic double getSalary(double raise)

in class LegalSecretary and

public double getSalary()

• in class Employee, then the method getSalaryis overloaded since the two methods have different parameter lists

• Both methods would be available in class LegalSecretary

Copyright © 2010

Inheritance & Overriding• How is all this useful?? Let’s consider an example:

• Creating/enhancing a computer game: we’ll consider the popular first-person shooter such as Halo• Other examples could be Call of Duty, Grand Theft Auto,

etc.

• A first-person shooter has many different weapons• We program all their common features in a base class• We derive new weapons from the base class, changing

how they behave via overriding• We do the same to create new vehicles from a base class

for vehicles, or create new monsters/aliens from a base class for monsters/aliens

Copyright © 2010

• Let’s quickly review the Student class hierarchy…

Copyright © 2010

Derived Classes

Copyright © 2010

Programming Examplepublic class Person {

private String name;

public Person( ) {name = "No name yet.";

}

public Person(String initialName) {name = initialName;

}

public void setName(String newName) {name = newName;

}

public String getName( ) {return name;

}

public String toString( ) {return "Name: " + name;

}

public boolean equals(Object other) {if (other instanceof Person) {

Person otherPerson = (Person) other;return (this.name.equalsIgnoreCase( otherPerson.name));

} else {return false;

}}

}

Person

String name

Person()

void setName(String)

String getName()

String toString()

boolean equals(Object)

Copyright © 2010

Programming Examplepublic class Student extends Person {

private int studentNumber;

public Student( ) {super( ); // explained laterstudentNumber = 0; // indicates no number yet

}

public Student(String initialName, int initialStudentNumber) {super(initialName);studentNumber = initialStudentNumber;

}

public void reset(String newName, int newStudentNumber) {setName(newName);setStudentNumber(newStudentNumber);

}

public int getStudentNumber( ) {return studentNumber;

}

public void setStudentNumber(int newStudentNumber) {studentNumber = newStudentNumber;

}

public String toString( ) {return("Name: " + getName( ) + "\nStudent number: " + studentNumber);

}

public boolean equals(Object other) {if (other instanceof Student) {

Student otherStudent = (Student)other;return (super.equals(otherStudent) && this.studentNumber == otherStudent.studentNumber);

} else {return false;

}}

}Copyright © 2010

Programming Examplepublic class Student extends Person {

private int studentNumber;

public Student( ) {super( ); // explained laterstudentNumber = 0; // indicates no number yet

}

public Student(String initialName, int initialStudentNumber) {super(initialName);studentNumber = initialStudentNumber;

}

public void reset(String newName, int newStudentNumber) {setName(newName);setStudentNumber(newStudentNumber);

}

public int getStudentNumber( ) {return studentNumber;

}

public void setStudentNumber(int newStudentNumber) {studentNumber = newStudentNumber;

}

public String toString( ) {return("Name: " + getName( ) + "\nStudent number: " + studentNumber);

}

public boolean equals(Object other) {if (other instanceof Student) {

Student otherStudent = (Student)other;return (super.equals(otherStudent) && this.studentNumber == otherStudent.studentNumber);

} else {return false;

}}

}

Student

int studentNumber

Student()

Student(String, int)

void reset(String, int)

int getStudentNumber()

void setStudentNumber(int)

String toString()

boolean equals(Object)

Person

String name

Person()

void setName(String)

String getName()

String toString()

boolean equals(Object) public void reset(String newName,

int newStudentNumber) {setName(newName);setStudentNumber(newStudentNumber);

}

Copyright © 2010

Private Instance Variables in the Base Class

• Private instance variables inherited from a base class cannot be accessed directly

• Instead, they must be accessed using methods that are declared public (i.e., the accessorsand mutators)

• While this may seem inconvenient, it provides an important mechanism for controlling access and changes to instance variables in the base class

Copyright © 2010

Private Methods in the Base Class

• Like private instance variables, private methods inherited from a base class cannot be accessed directly

• Instead, they, too, must be accessed using a method that is declared public

• This, too, provides an important mechanism for controlling access to methods in the base class

• Since private methods typically serve as helper methods, their use is always limited to the class in which they are defined

Copyright © 2010

Constructors in Derived Classes

• A base class has its own constructors• Their purpose typically is to initialize the instance

variables declared in the base class

• A derived class has its own constructors• Their purpose typically is to call a constructor of the

base class, and then to initialize the instance variables declared in the derived class

Copyright © 2010

Constructors in Derived Classes

• To call a constructor of the base class, usesuper(Values_for_Instance_Variables

_Declared_in_the_Base_Class);

• Examplesuper(initialName);

notPerson(initialName); // ILLEGAL

Copyright © 2010

Programming Examplepublic class Student extends Person {

private int studentNumber;

public Student( ) {super( ); // explained laterstudentNumber = 0; // indicates no number yet

}

public Student(String initialName, int initialStudentNumber) {super(initialName);studentNumber = initialStudentNumber;

}

public void reset(String newName, int newStudentNumber) {setName(newName);setStudentNumber(newStudentNumber);

}

public int getStudentNumber( ) {return studentNumber;

}

public void setStudentNumber(int newStudentNumber) {studentNumber = newStudentNumber;

}

public String toString( ) {return("Name: " + getName( ) + "\nStudent number: " + studentNumber);

}

public boolean equals(Object other) {if (other instanceof Student) {

Student otherStudent = (Student)other;return (super.equals(otherStudent) && this.studentNumber == otherStudent.studentNumber);

} else {return false;

}}

}

public Student( ) {super( );studentNumber = 0;

}

public Student(String initialName, int initialStudentNumber) {super(initialName);studentNumber = initialStudentNumber;

}

Copyright © 2010

Programming Examplepublic class Person {

private String name;

public Person( ) {name = "No name yet.";

}

public Person(String initialName) {name = initialName;

}

public void setName(String newName) {name = newName;

}

public String getName( ) {return name;

}

public String toString( ) {return "Name: " + name;

}

public boolean equals(Object other) {if (other instanceof Person) {

Person otherPerson = (Person) other;return (this.name.equalsIgnoreCase( otherPerson.name));

} else {return false;

}}

}

public Person( ) {name = "No name yet.";

}

public Person(String initialName) {name = initialName;

}

Copyright © 2010

Using super

• The call to the constructor of the base class (using super) must be the first action taken in the constructor of a derived class

• When no call to a constructor of the base class is included, Java automatically includes a call to the default constructor of the base class• The default constructor is the one that does not take

any arguments• If the base class does not have a default constructor,

you must use super to call one of the alternate constructors

Copyright © 2010

Using super

• Equivalent definitions:public Student() {

super();studentNumber = 0;

}

• andpublic Student() {

studentNumber = 0;}

• The first is probably preferred since it makes it clear what work is being done

Copyright © 2010

The this Method

• Within the definition of one constructor, it can be appropriate to call another constructor in the same class

• The keyword this is used to call another constructor in the same class (we saw this several lectures ago)

• Example, add another constructor:public Student (String initialName) {

this(initialName, 0) // call other ctor}

Copyright © 2010

The this Method

• Any use of this must be the first action in the constructor definition

• Thus, a constructor definition cannot contain a call using super and a call using this

• Advanced: To use both super and this…• Include a call using this in the one constructor and a

call using super in the called constructor

Copyright © 2010

Changes to Common Behavior

• Let’s return to our previous company/employee example

• Imagine a company-wide change affecting all employees

• Example: Everyone is given a $10,000 raise due to inflation• The base employee salary is now $50,000• Legal secretaries now make $55,000• Marketers now make $60,000

• We must modify our code to reflect this policy change

Copyright © 2010

Modifying the Superclass// A class to represent employees (20-page manual)public class Employee {

public int getHours() {return 40; // works 40 hours / week

}

public double getSalary() {return 50000.0; // $50,000.00 / year

}...

}

• Are we finished?

• The Employee subclasses are still incorrect• Some have overridden getSalary to return other

valuesCopyright © 2010

An Unsatisfactory Solutionpublic class LegalSecretary extends Secretary {

public double getSalary() {return 55000.0;

}...

}public class Marketer extends Employee {

public double getSalary() {return 60000.0;

}...

}

• Problem: We had to make adjustments in 3 places

• The subclasses' salaries are based on the Employee salary, but the getSalary code does not reflect this

Copyright © 2010

Calling Overridden Methods

• Subclasses can call overridden methods with super

super.method(parameters)

• Example:public class LegalSecretary extends Secretary {

public double getSalary() {double baseSalary = super.getSalary();return baseSalary + 5000.0;

}...

}

Copyright © 2010

Calling Overridden Methods• However, you cannot repeat the use of super to

invoke a method in some ancestor class other than the immediate base class• E.g., you cannot do super.super.toString();

• Exercise: Modify Lawyer and Marketer to use super

Copyright © 2010

Improved Subclassespublic class Lawyer extends Employee {

public String getVacationForm() {return "pink";

}public int getVacationDays() {

return super.getVacationDays() + 5;}public void sue() {

System.out.println("I'll see you in court!");}

}

public class Marketer extends Employee {public void advertise() {

System.out.println("Act now while supplies last!");}public double getSalary() {

return super.getSalary() + 10000.0;}

}

Copyright © 2010

Announcements

• Read Sections 9.3-9.4

• Any Questions?!?!

Copyright © 2010

• Quick review…

Copyright © 2010

Derived Classes

Copyright © 2010

Programming Examplepublic class Person {

private String name;

public Person( ) {name = "No name yet.";

}

public Person(String initialName) {name = initialName;

}

public void setName(String newName) {name = newName;

}

public String getName( ) {return name;

}

...

Copyright © 2010

Programming Example...

public String toString( ) {return "Name: " + name;

}

public boolean equals(Object other) {if (other instanceof Person) {

Person otherPerson = (Person) other;return (this.name.equalsIgnoreCase( otherPerson.name));

} else {return false;

}}

}

Copyright © 2010

Programming Examplepublic class Student extends Person {

private int studentNumber;

public Student( ) {super( ); // explained laterstudentNumber = 0; // indicates no number yet

}

public Student(String initialName, int initialStudentNumber) {super(initialName);studentNumber = initialStudentNumber;

}

public void reset(String newName, int newStudentNumber) {setName(newName);setStudentNumber(newStudentNumber);

}

public int getStudentNumber( ) {return studentNumber;

}

...

Copyright © 2010

Programming Example...

public void setStudentNumber(int newStudentNumber) {studentNumber = newStudentNumber;

}

public String toString( ) {return("Name: " + getName( ) + "\nStudent number: " + studentNumber);

}

public boolean equals(Object other) {if (other instanceof Student) {

Student otherStudent = (Student)other;return (super.equals(otherStudent)

&& this.studentNumber == otherStudent.studentNumber);} else {

return false;}

}

}

Copyright © 2010

Multilevel Derived Classes• Class Undergraduate can be derived from

class Student which is derived from class Person

• Class Undergraduate will have all the instance variables and methods of class Student which has all the instance variables and methods of class Person

• To keep things simple, each Undergraduatewill only contain an indicator for their student level (freshmen, sophomore, etc.)

Copyright © 2010

Programming Examplepublic class Undergraduate extends Student {

private int level; // 1 for freshman, 2 for sophomore,// 3 for junior, or 4 for senior.

public Undergraduate( ) {super( );level = 1;

}

public Undergraduate(String initialName,int initialStudentNumber, int initialLevel) {

super(initialName, initialStudentNumber);setLevel(initialLevel); // Checks 1 <= initialLevel <= 4

}

public void reset(String newName, int newStudentNumber, int newLevel) {reset(newName, newStudentNumber);setLevel(newLevel); // Checks 1 <= newLevel <= 4

}

public int getLevel( ) {return level;

}...

Copyright © 2010

Programming Example...public void setLevel(int newLevel) {

if ((1 <= newLevel) && (newLevel <= 4)) {level = newLevel;

} else {throw new IllegalArgumentException("Invalid student level.");

}}

public String toString( ) {return (super.toString( ) + "\nStudent Level: " + level);

}

public boolean equals(Object other) {boolean result = false;if (other instanceof Undergraduate) {

Undergraduate otherUndergraduate = (Undergraduate) other;result = (super.equals(otherUndergraduate)

&& (this.level == otherUndergraduate.level));}return result;

}}

Copyright © 2010