1 Object- Oriented Programming (CS206) Object-Oriented Relationships.

Slides:



Advertisements
Similar presentations
Object Oriented Programming
Advertisements

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 1 Abstract Classes and Interfaces.
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
UFCE3T-15-M Programming part 1 UFCE3T-15-M Object-oriented Design and Programming Block2: Inheritance, Polymorphism, Abstract Classes and Interfaces Jin.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 9: Inheritance and Interfaces.
1 Inheritance Readings: Writing classes Write an Employee class with methods that return values for the following properties of employees at a.
1 Inheritance and Polymorphism. 2 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common.
Copyright 2008 by Pearson Education Building Java Programs Chapter 9 Lecture 9-1: Inheritance reading:
Copyright 2010 by Pearson Education Topic 31 - inheritance.
Chapter 11 Abstract Classes and Interfaces 1. Abstract method New modifier for class and method: abstract An abstract method has no body Compare: abstract.
CISC6795: Spring Object-Oriented Programming: Polymorphism.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 11 Inheritance and Polymorphism.
Inheritance and Polymorphism Daniel Liang, Introduction to Java Programming.
1 1 Abstract Classes and Interfaces. 22 Motivations You learned how to write simple programs to display GUI components. Can you write the code to respond.
CSC 142 Computer Science II Zhen Jiang West Chester University
Copyright 2008 by Pearson Education Building Java Programs Chapter 8 Lecture 19: encapsulation, inheritance reading: (Slides adapted from Stuart.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 1 Chapter 13 Abstract Classes and Interfaces.
Copyright 2008 by Pearson Education Building Java Programs Chapter 9 Lecture 9-1: Inheritance reading:
Some Object-Oriented Programming (OOP) Review. Let’s practice writing some classes Write an Employee class with methods that return values for the following.
1 final (the keyword, not the exam). 2 Motivation Suppose we’ve defined an Employee class, and we don’t want someone to come along and muck it up  E.g.,
1 Building Java Programs Chapter 9: Inheritance and Interfaces These lecture notes are copyright (C) Marty Stepp and Stuart Reges, They may not be.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
1 Abstract Classes and Interfaces. 2 The abstract Modifier  The abstract class –Cannot be instantiated –Should be extended and implemented in subclasses.
Copyright 2008 by Pearson Education Building Java Programs Chapter 9 Lecture 9-2: Static Data; More Inheritance reading:
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 10 Inheritance and.
Object Oriented Programming
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Copyright 2010 by Pearson Education Building Java Programs Chapter 9 Lecture 9-1: Inheritance reading: 9.1.
1 Advanced Programming Inheritance (2). 2 Inheritance Inheritance allows a software developer to derive a new class from an existing one The existing.
Interfaces F What is an Interface? F Creating an Interface F Implementing an Interface F What is Marker Interface?
Copyright 2008 by Pearson Education Building Java Programs Chapter 9 Lecture 9-2: Interacting with the Superclass ( super ) reading:
Object Oriented programming Instructor: Dr. Essam H. Houssein.
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 1 Chapter 15 Abstract Classes and Interfaces.
Copyright 2008 by Pearson Education Building Java Programs Chapter 9: Inheritance and Interfaces Lecture 9-1.
Lecture 5:Interfaces and Abstract Classes Michael Hsu CSULA.
Lecture 6:Interfaces and Abstract Classes Michael Hsu CSULA.
Lecture 5:Interfaces and Abstract Classes
Chapter 15 Abstract Classes and Interfaces
Building Java Programs Chapter 9
Building Java Programs Chapter 9
The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs. Large-scale projects face.
Lecture 15: More Inheritance
Lecture 9-2: Interacting with the Superclass (super);
Road Map Inheritance Class hierarchy Overriding methods Constructors
Chapter 13 Abstract Classes and Interfaces
Adapted from slides by Marty Stepp and Stuart Reges
OBJECT ORIENTED PROGRAMMING II LECTURE 8 GEORGE KOUTSOGIANNAKIS
Chapter 12 Abstract Classes and Interfaces
The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs. Large-scale projects face.
Building Java Programs
Building Java Programs
Law firm employee analogy
Lecture 14: Inheritance Building Java Programs: A Back to Basics Approach by Stuart Reges and Marty Stepp Copyright (c) Pearson All rights reserved.
Building Java Programs
Topic 31 - inheritance.
Building Java Programs
Inheritance Readings: 9.1.
Lecture 15: Inheritance II
Chapter 14 Abstract Classes and Interfaces
Building Java Programs
Building Java Programs
Building Java Programs
Chapter 11 Inheritance and Polymorphism Part 1
Building Java Programs
Building Java Programs
Chapter 11 Inheritance and Encapsulation and Polymorphism
Presentation transcript:

1 Object- Oriented Programming (CS206) Object-Oriented Relationships

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 ; // $40, / 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 ; // $40, / 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 ; // $50, / year }

9 Superclasses and Subclasses GeometricObject1 Circle4 Rectangle1 TestCircleRectangle Run

Implementing Object-Oriented Relationships : is a 10 “ employee is a person ” class Person { } Is a relationship is implemented by making a class extends another class class Employee extends Person { } Inheritance “ car loan is a loan ” class Loan { } class CarLoan extends Loan { }

11 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 Test{ public static void main (String [] arg){ B b1=new B(); b1.i=10; b1.m1(); }} class A{ int i; int j; void m1(){} } class B extends A{ int k; void m2(){} } Inheritance: is a relationship class Loan{} class CarLoan extends Loan {}

12 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"). Inheritance: is a relationship

13 SubclassesSuperclass GraduateStudent, UndergraduateStudentStudent Circle, Triangle, RectangleShape CarLoan, HomeImprovementLoan, MortgageLoan Loan SaliredEmployee,CommisionEmployeeEmployee CheckingAccount, SavingsAccountBankAccount Inheritance examples. 13 class Employee { } class CommisionEmployee extends employee {……………….. } class SaliredEmployee extends employee {…………….. } UML Employee Hierarchy Diagram UML defines inheritance as a generalization relation

14 Case Study: Law Firm Consider a law firm with many types of employees. common rules: hours, vacation time, benefits, regulations,... all employees attend common orientation to learn general rules each employee receives 20-page manual of the common rules each subdivision also has specific 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"...) UML defines inheritance as a generalization relation Why not just have a 22 page Lawyer manual, a 21-page Secretary manual, a 23-page Marketer manual, etc.?

A Simple Inheritance case study 15 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(){ returnregisterationNumber; } } public class Test{ public static void main (String [] arg) { Student student1=new Student(); student1.setName ("Ahmed Hussien"); student1.setRegisterationNumber(4564); } public class Test{ public static void main (String [] arg) { Student student1=new Student(); student1.setName ("Ahmed Hussien"); student1.setRegisterationNumber(4564); }

16  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. Calling a subclass constructor invokes super class constructor

 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. 17 public class Employee{ String firstName; String lastName; public Employee( String first, String last) { firstName = first; lastName = last; } /// } 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; } class ComissionEmployee extends Employee { private double comission; public ComissionEmployee( String first, String last,double com ) { super( first, last); comission=com; }

18 class B Class A 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 inheritance hierarchy More general More Specific More general More Specific

19 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.

Modifier : abstract  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. 20 public abstract class M { abstract public void m1(); void m2() { }  A method or a class can be declared as abstract.  Access modifiers and abstract keyword can appear in any order. abstract method

21 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.

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. 22 abstract class Player { int age; public int getAge() {return age;} public abstract void play (); } class FootbalPlayer extends Player { public void play () { …………….. }

23 public abstract class Shape { public abstract double calculateArea(); } public class Circle extends Shape { private double radius; public Circle(double radius){ this.radius=radius; } public double calculateArea() { return 3.14*radius*radius; } 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; } Example : extending abstract class Abstract elements are italic in UML Diagrams

 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. class Company implements Payable{ public double getPaymentAmount() { //// } public interface Payable { double getPaymentAmount(); } Implementing Object-Oriented Relationships : provides a Company provides Payable

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").

28 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; }

29 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.

30 Overriding vs. Overloading

31 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.

32 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 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.

33 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.

34 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(); }

35 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.

 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

37 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. VariablesConstructorsMethods Abstract class No restrictionsConstructors are invoked by subclasses through constructor chaining. An abstract class cannot be instantiated using the new operator. No restrictions. InterfaceAll 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

38 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 parent- child 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.

39 Casestudy :Payable interface public interface Payable { double getPaymentAmount(); } 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; } 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; }

40

41