Object Oriented Programming CS 206 ObjectOriented Relationships 1

Object- Oriented Programming (CS 206) Object-Oriented Relationships 1

An Employee class // A class to represent employees in general (20 -page manual). public class Employee { public int get. Hours() { return 40; // works 40 hours / week } public double get. Salary() { return 40000. 0; // $40, 000. 00 / year } public int get. Vacation. Days() { return 10; // 2 weeks' paid vacation } } public String get. Vacation. Form() { 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 get. Hours() { return 40; // works 40 hours / week } public double get. Salary() { return 40000. 0; // $40, 000. 00 / year } public int get. Vacation. Days() { return 10; // 2 weeks' paid vacation } public String get. Vacation. Form() { return "yellow"; // use the yellow form } } public void take. Dictation(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 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 get. Hours, get. Salary, get. Vacation. Days, and get. Vacation. Form 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 take. Dictation(String text) { System. out. println("Taking dictation of text: " + text); } } • Now we only write the parts unique to each type. – Secretary inherits get. Hours, get. Salary, get. Vacation. Days, and get. Vacation. Form methods from Employee. – Secretary adds the take. Dictation method.

Lawyer class // A class to represent lawyers. public class Lawyer extends Employee { // overrides get. Vacation. Form from Employee class public String get. Vacation. Form() { return "pink"; } // overrides get. Vacation. Days from Employee class public int get. Vacation. Days() { 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 get. Salary() { return 50000. 0; // $50, 000. 00 / year }

Superclasses and Subclasses Geometric. Object 1 Circle 4 Rectangle 1 Test. Circle. Rectangle Run 9

Implementing Object-Oriented Relationships : is a “ employee is a person ” class Person { class Employee extends Person { } } “ car loan is a loan ” class Car. Loan 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 Car. Loan extends Loan {} class A{ int i; int j; void m 1(){} } class B extends A{ int k; void m 2(){} } class Test{ public static void main (String [] arg){ B b 1=new B(); b 1. i=10; b 1. m 1(); }} 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 Graduate. Student, Undergraduate. Student Shape Circle, Triangle, Rectangle Loan Car. Loan, Home. Improvement. Loan, Mortgage. Loan Employee Salired. Employee, Commision. Employee Bank. Account Checking. Account, Savings. Account UML Employee Hierarchy Diagram class Employee { } class Commision. Employee extends employee {………………. . } class Salired. Employee 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 set. Name (String name){ this. name=name; } public String get. Name(){ return name; } } public class Student extends Person{ private int registeration. Number; public Student () {} public void set. Registeration. Number (int registeration. Number){ this. registeration. Number=registeration. Number; } public int get. Registeration. Number(){ return registeration. Number; } } public class Test{ public static void main (String [] arg) { Student student 1=new Student(); student 1. set. Name ("Ahmed Hussien"); student 1. set. Registeration. Number(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. 16

q You can use the super keyword in the subclass constructor to invoke another superclass constructor rather than the default. q In a constructor, super can only appear at the first line, otherwise will cause a compile error. public class Employee{ String first. Name; String last. Name; public Employee( String first, String last) { first. Name = first; last. Name = last; } /// } class Comission. Employee extends Employee { private double comission; public Comission. Employee( String first, String last, double com ) { super( first, last); comission=com; } } 17

inheritance hierarchy Class A More Specific general Specific 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 m 1(); void m 2() { } } 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 get. Age() {return age; } public abstract void play (); } class Footbal. Player extends Player { public void play () { ……………. . } } 22

Example : extending abstract class public abstract class Shape { public abstract double calculate. Area(); } public class Rectangle extends Shape{ private double height, width; public Rectangle( double height, double width) { this. height=height; this. width=width; } public double calculate. Area() { return height*width; } public class Circle extends Shape { private double radius; public Circle(double radius){ this. radius=radius; } public double calculate. Area() { return 3. 14*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 get. Payment. Amount(); } class Company implements Payable{ public double get. Payment. Amount() { //// } }

• Design an abstract class named Bank. Account 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}, Calc. Interest() { update balance by amount = balance * (annual interest rate /12)}, and Monthly. Pocess() {subtract the monthly service charge from balance, call calc. Interest method, set number of deposit, number of withdrawals and monthly service charges to zero}. • Next, design a Saving. Account class which inherits from Bank. Account 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 Monthly. Process() {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 get. Author() to return author value and get. Title() 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 Phone. Book { public boolean insert(String phone. Num, String name) {. . . } public String get. Phone. Number(String name) {. . . } public String get. Name(String phone. Num) {. . . } // other private fields and methods } • Phone. Book 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. get. Phone. Number() and get. Name() return null if they cannot find the desired entry in the Phone. Book. • Design and implement a subclass of Phone. Book called Yellow. Pages (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 Geometric. Object { // Other methods are omitted /** Override the to. String method defined in Geometric. Object */ public String to. String() { return super. to. String() + "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 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. 31

The to. String() method in Object The to. String() 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. to. String()); The code displays something like Loan@15037 e 5. This message is not very helpful or informative. Usually you should override the to. String 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 Interface. Name { constant declarations; method signatures; } Example: public interface Edible { /** Describe how to eat */ public abstract String how. To. Eat(); } 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 No restrictions. through constructor chaining. An abstract class cannot be instantiated using the new operator. Interface All variables must be public static final No constructors. An interface cannot be instantiated using the new operator. 37 All methods must be public abstract instance methods 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 “Object. Oriented Modeling, ” for more discussions. 38 38

Casestudy : Payable interface public interface Payable { double get. Payment. Amount(); } public class Employee implements Payable { private int days; private double day. Wage; Employee(int days, double day. Wage ) { this. days=days; this. day. Wage=day. Wage; } public double get. Payment. Amount() { return day. Wage*days; } } public class Invoice implements Payable { private int quantity; private double price. Per. Item; Invoice(int quantity, double price. Per. Item ) { this. quantity=quantity; this. price. Per. Item=price. Per. Item; } public double get. Payment. Amount() { return quantity*price. Per. Item; } } 39

40
- Slides: 40