abstract class.

advertisement
Object- Oriented Programming
(CS243)
Lecture 6
Object-Oriented Relationships
1
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.)
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);
}
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 class that is being extended.
– subclass: The child class that extends the superclass and
inherits its behavior.
• Subclass gets a copy of every field and method from superclass
Inheritance syntax
public 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)
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 getVacationForm
methods from Employee.
– Secretary adds the takeDictation method.
Lawyer class
// A class to represent lawyers.
public class Lawyer extends Employee {
// overrides getVacationForm from Employee class
public String getVacationForm() {
return "pink";
}
// overrides getVacationDays from Employee class
public 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.
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
}
}
Superclasses and Subclasses
GeometricObject
-color: String
The color of the object (default: white).
-filled: boolean
Indicates whether the object is filled with a color (default: false).
-dateCreated: java.util.Date
The date when the object was created.
+GeometricObject()
Creates a GeometricObject.
+GeometricObject(color: String,
filled: boolean)
Creates a GeometricObject with the specified color and filled
values.
+getColor(): String
Returns the color.
+setColor(color: String): void
Sets a new color.
+isFilled(): boolean
Returns the filled property.
+setFilled(filled: boolean): void
Sets a new filled property.
+getDateCreated(): java.util.Date
Returns the dateCreated.
+toString(): String
Returns a string representation of this object.
GeometricObject1
Rectangle
Circle
-radius: double
-width: double
+Circle()
-height: double
+Circle(radius: double)
+Rectangle()
+Circle(radius: double, color: String,
filled: boolean)
+Rectangle(width: double, height: double)
+getRadius(): double
+Rectangle(width: double, height: double
color: String, filled: boolean)
+setRadius(radius: double): void
+getWidth(): double
+getArea(): double
+setWidth(width: double): void
+getPerimeter(): double
+getHeight(): double
+getDiameter(): double
+setHeight(height: double): void
+printCircle(): void
+getArea(): double
+getPerimeter(): double
9
Circle4
Rectangle1
TestCircleRectangle
Run
Implementing Object-Oriented Relationships : is a
“ employee is a person ”
class Person
{
class Employee extends Person
{
}
}
“ car loan is a loan ”
class CarLoan extends Loan
class Loan
{
{
}
}
Inheritance
Is a relationship is implemented by making a class extends another class
10
Inheritance: is a relationship
• When creating a class, rather than declaring completely
new members, the programmer can designate that the
new class inherit the members of an existing class.
• The existing class is called the superclass, and the new
class is the subclass.
• A subclass normally adds its own fields and methods.
class Loan{}
class CarLoan extends Loan {}
class A{
int i;
int j;
void m1(){}
}
class B extends A{
int k;
void m2(){}
}
class Test{
public static void main (String [] arg){
B b1=new B();
b1.i=10;
b1.m1();
}}
11
Inheritance: is a relationship
• Each subclass can become the superclass for future
subclasses.
• Multiple inheritance is not allowed.
• In Java, the class hierarchy begins with class
java.lang.Object which every class in Java directly or
indirectly extends (or "inherits from").
12
Inheritance examples.
Superclass
Subclasses
Student
GraduateStudent, UndergraduateStudent
Shape
Circle, Triangle, Rectangle
Loan
CarLoan, HomeImprovementLoan, MortgageLoan
Employee
SaliredEmployee,CommisionEmployee
BankAccount
CheckingAccount, SavingsAccount
UML Employee Hierarchy Diagram
class Employee
{
}
class CommisionEmployee extends employee
{………………..
}
class SaliredEmployee extends employee
{……………..
}
UML defines inheritance as a generalization relation
13
Case Study: Law Firm
Consider a law firm with many types of employees.
•
common rules: hours, vacation time, benefits, regulations, ...
•
each subdivision also has specific rules
• all employees attend common orientation to learn general rules
• each employee receives 20-page manual of the common rules
• employee attends a subdivision-specific orientation to learn them
• employee receives a smaller (1-3 page) manual of these rules
• smaller manual adds some rules and also changes some rules from the
large manual ("use the pink form instead of yellow form"...)
Why not just have a 22 page Lawyer manual, a 21-page Secretary manual, a 23-page
Marketer manual, etc.?
14
UML defines inheritance as a generalization relation
A Simple Inheritance case study
public class Person{
private String name;
public Person ()
{}
public void setName (String name){
this.name=name;
}
public String getName(){
return name;
}
public class Student extends Person{
private int registerationNumber;
public Student ()
{}
public void setRegisterationNumber (int registerationNumber){
this.registerationNumber=registerationNumber;
}
public int getRegisterationNumber(){
return registerationNumber;
}
}
}
public class Test{
public static void main (String [] arg)
{
Student student1=new
Student();
student1.setName ("Ahmed Hussien");
student1.setRegisterationNumber(4564);
}
}
15
Calling a subclass constructor invokes super class constructor
Creating an instance of sub class means automatically creating an instance of the super
class by invoking the default no argument constructor.
Java adds automatically super() to the first line in the constructor of sub class to invoke
the default no argument constructor of the super class.
public B() {
}
public B(double d) {
// some statements
}
public B() {
super();
}
is equivalent to
is equivalent to
public B(double d) {
super();
// some statements
}
16
 You can use the super keyword in the subclass constructor to invoke another superclass
constructor rather than the default.
 In a constructor, super can only appear at the first line, otherwise will cause a compile error.
public class Employee{
String firstName;
String lastName;
public Employee( String first, String last)
{
firstName = first;
lastName = last;
} ///
}
class ComissionEmployee extends Employee
{
private double comission;
public ComissionEmployee( String first, String last,double com )
{
super( first, last);
comission=com;
}
}
17
inheritance hierarchy
Class A
More
Specific
general
general
Specific
More
More
More
class B
class c
In the inheritance hierarchy, classes become more specific and concrete with each new
subclass. If you move from a subclass back up to a superclass, the classes become more general
and less specific.
Class design should ensure that a superclass contains common features of its subclasses.
More generalialization means reaching the abstraction level
18
Example
• Imagine a publishing company that markets both Book and
audio-CD versions of its works. Create a class publication
that stores the title (string), price (float) and sales (array of
three floats) of a publication.
• This class is used as base class for two classes: Book which
has page count (int) and audio-CD which has playing time in
minutes (float). Each of these three classes should have a
get_data() and display_data() methods.
• Write a Main class to create Book and audio-CD objects,
asking user to fill in their data with get_data( ) method, and
then displaying data with display_data( ) method.
19
Modifier : abstract
A method or a class can be declared as abstract.
Access modifiers and abstract keyword can appear in any order.
abstract method
 An abstract method is just a method signature without any
implementation.
 abstract methods cannot have a body.
 A constructor can never be declared as abstract.
 If a class has any abstract methods it must be declared as abstract.
public abstract class M
{
abstract public void m1();
void m2()
{
}
}
20
abstract method in abstract class
An abstract method cannot be contained in a
nonabstract class. If a subclass of an abstract
superclass does not implement all the abstract
methods, the subclass must be defined abstract. In
other words, in a nonabstract subclass extended from
an abstract class, all the abstract methods must be
implemented, even if they are not used in the
subclass.
21
21
abstract class
 Sometimes a superclass is abstract that it cannot have any specific
instances. Such a class is referred to as an abstract class.
 no objects can be created from an abstract class.
 An abstract class forces its user to create a subclass to execute
instance methods
 Subclasses of this abstract class will have to implement the abstract
methods of abstract class or declared as abstract themselves.
 A class can be declared abstract even if no abstract methods is
included.
abstract class Player
{
int age;
public int getAge()
{return age;}
public abstract void play ();
}
class FootbalPlayer extends Player
{
public void play ()
{
……………..
}
}
22
Example : extending abstract class
public abstract class Shape {
public abstract double calculateArea();
}
public class Rectangle extends Shape{
private double height, width;
public Rectangle( double height,double width)
{
this.height=height;
this.width=width;
}
public double calculateArea()
{
return height*width;
}
public class Circle extends Shape {
private double radius;
public Circle(double radius){
this.radius=radius;
}
public double calculateArea()
{
return 3.14*radius*radius;
}
}
}
Abstract elements are italic in UML Diagrams
23
Implementing Object-Oriented Relationships : provides a
An interface is a classlike that contains only constants and abstract
methods and no constructors.
A class implements an interface by implementing all methods in the
interface.
An interface represents the relation “provides a”(promises).
If a class is declared to implement an interface and does not
implement all the methods in the interface , it must be declared abstract
otherwise a compile error
An interface can extend one or more interfaces..
A class can implements more than one interface.
Company provides Payable
public interface Payable
{
double getPaymentAmount();
}
class Company implements Payable{
public double getPaymentAmount()
{
////
}
}
• Design an abstract class named BankAccount with data: balance,
number of deposits this month, number of withdrawals, annual
interest rate, and monthly service charges.
• The class has constructor and methods: Deposit (amount) {add
amount to balance and increment number of deposit by one},
Withdraw (amount) {subtract amount from balance and increment
number of withdrawals by one}, CalcInterest() { update balance by
amount = balance * (annual interest rate /12)}, and MonthlyPocess()
{subtract the monthly service charge from balance, call calcInterest
method, set number of deposit, number of withdrawals and
monthly service charges to zero}.
• Next, design a SavingAccount class which inherits from BankAccount
class. The class has Boolean status field to represent the account is
active or inactive {if balance falls below $25}. No more withdrawals
if account is inactive.
• The class has methods Deposit () {determine if account inactive then
change the status after deposit above $25, then call base deposit
method}, Withdraw() method check the class is active then call
base method, and MonthlyProcess() {check if number of
withdrawals more than 4, add to service charge $1 for each
withdrawals above 4}
• Consider designing and implementing a set of classes to
represent books, library items, and library books.
• a) An abstract class library item contains two pieces of
information: a unique ID (string) and a holder (string). The
holder is the name of person who has checked out this item.
The ID can not change after it is created, but the holder can
change.
• b) A book class inherits from library item class. It contains data
author and title where neither of which can change once the
book is created. The class has a constructor with two
parameters author and title, and two methods getAuthor() to
return author value and getTitle() to return title value.
• c) A library book class is a book that is also a library item
(inheritance). Suggest the required data and method for this
class.
• d) A library is a collection of library books (Main class) which
has operations: add new library book to the library, check out
a library item by specifying its ID, determine the current
holder of library book given its ID
You have been provided with the following class that implements a
phone number directory:
public class PhoneBook {
public boolean insert(String phoneNum, String name) { ... }
public String getPhoneNumber(String name) { ... }
public String getName(String phoneNum) { ... }
// other private fields and methods }
• PhoneBook does not accept phone numbers that begin with "0" or
"1", that do not have exactly 10 digits. It does not allow duplicate
phone numbers. insert() returns true on a successful phone number
insertion, false otherwise. getPhoneNumber() and getName() return
null if they cannot find the desired entry in the PhoneBook.
• Design and implement a subclass of PhoneBook called YellowPages
(including all of the necessary fields and methods) that supports the
following additional operations.
• Retrieve the total number of phone numbers stored in the directory.
• Retrieve the percentage of phone numbers stored in the directory
that are "810" numbers (that have area code "810").
Overriding Methods in the Superclass
A subclass inherits methods from a superclass. Sometimes it is necessary for the subclass
to modify the implementation of a method defined in the superclass. This is referred to as
method overriding.
public class Circle extends GeometricObject {
// Other methods are omitted
/** Override the toString method defined in GeometricObject */
public String toString() {
return super.toString() + "\nradius is " + radius;
}
}
28
NOTE
An instance method can be overridden only
if it is accessible. Thus a private method
cannot be overridden, because it is not
accessible outside its own class. If a method
defined in a subclass is private in its
superclass, the two methods are completely
unrelated.
29
Overriding vs. Overloading
public class Test {
public static void main(String[] args) {
A a = new A();
a.p(10);
a.p(10.0);
}
}
public class Test {
public static void main(String[] args) {
A a = new A();
a.p(10);
a.p(10.0);
}
}
class B {
public void p(double i) {
System.out.println(i * 2);
}
}
class B {
public void p(double i) {
System.out.println(i * 2);
}
}
class A extends B {
// This method overrides the method in B
public void p(double i) {
System.out.println(i);
}
}
class A extends B {
// This method overloads the method in B
public void p(int i) {
System.out.println(i);
}
}
30
The Object Class and Its Methods
Every class in Java is descended from the
java.lang.Object class. If no inheritance is
specified when a class is defined, the
superclass of the class is Object.
public class Circle {
...
}
public class Circle extends Object {
...
}
Equivalent
31
The toString() method in Object
The toString() method returns a string representation of the
object. The default implementation returns a string consisting
of a class name of which the object is an instance, the at sign
(@), and a number representing this object.
Loan loan = new Loan();
System.out.println(loan.toString());
The code displays something like Loan@15037e5 . This
message is not very helpful or informative. Usually you should
override the toString method so that it returns a digestible string
representation of the object.
32
What is an interface?
Why is an interface useful?
An interface is a classlike construct that contains
only constants and abstract methods. In many
ways, an interface is similar to an abstract class,
but the intent of an interface is to specify behavior
for objects. For example, you can specify that the
objects are comparable, edible, cloneable using
appropriate interfaces.
33
33
Define an Interface
To distinguish an interface from a class, Java uses the
following syntax to define an interface:
public interface InterfaceName {
constant declarations;
method signatures;
}
Example:
public interface Edible {
/** Describe how to eat */
public abstract String howToEat();
}
34
34
Interface is a Special Class
An interface is treated like a special class in Java.
Each interface is compiled into a separate
bytecode file, just like a regular class. Like an
abstract class, you cannot create an instance from
an interface using the new operator, but in most
cases you can use an interface more or less the
same way you use an abstract class. For example,
you can use an interface as a data type for a
variable, as the result of casting, and so on.
35
35
 Interface names may be adjectives or nouns.
 Variables in interfaces are implicitly static and final and should
be initialized with a value.
 Methods in interface are implicitly public (even if left
without a modifier) and abstract(even if abstract modifier is
not declared), they should only be implemented only by
public methods.
 Methods declared in an interface can be declared as abstract
(although unneeded).
36
Interfaces vs. Abstract Classes
In an interface, the data must be constants; an abstract class can
have all types of data.
Each method in an interface has only a signature without
implementation; an abstract class can have concrete methods.
Variables
Constructors
Methods
Abstract
class
No restrictions
Constructors are invoked by subclasses
through constructor chaining. An abstract
class cannot be instantiated using the
new operator.
No restrictions.
Interface
All variables
must be public
static final
No constructors. An interface cannot be
instantiated using the new operator.
All methods must be
public abstract
instance methods
37
37
Whether to use an interface or a class?
Abstract classes and interfaces can both be used to model common
features. How do you decide whether to use an interface or a class?
In general, a strong is-a relationship that clearly describes a parentchild relationship should be modeled using classes. For example, a
staff member is a person. So their relationship should be modeled
using class inheritance. A weak is-a relationship, also known as an
is-kind-of relationship, indicates that an object possesses a certain
property. A weak is-a relationship can be modeled using interfaces.
For example, all strings are comparable, so the String class
implements the Comparable interface. You can also use interfaces
to circumvent single inheritance restriction if multiple inheritance is
desired. In the case of multiple inheritance, you have to design one
as a superclass, and others as interface. See Chapter “ObjectOriented Modeling,” for more discussions.
38
38
Casestudy :Payable interface
public interface Payable
{
double getPaymentAmount();
}
public class Employee implements Payable
{
private int days;
private double dayWage;
Employee(int days,double dayWage )
{
this.days=days;
this.dayWage=dayWage;
}
public double getPaymentAmount()
{
return dayWage*days;
}
}
public class Invoice implements Payable
{
private int quantity;
private double pricePerItem;
Invoice(int quantity,double pricePerItem )
{
this.quantity=quantity;
this.pricePerItem=pricePerItem;
}
public double getPaymentAmount()
{
return quantity*pricePerItem;
}
}
39
40
Download