Java_5 Object-Oriented Programming: Inheritance. Outline 5.1 Introduction

Java_5 Object-Oriented Programming: Inheritance Outline 5.1 5.2 5.3 5.4 5.5 5.6 5.7 5.8 Introduction Superclasses and Subclasses protected Members Re...
Author: Guest
15 downloads 0 Views 103KB Size
Java_5 Object-Oriented Programming: Inheritance Outline 5.1 5.2 5.3 5.4 5.5 5.6 5.7 5.8

Introduction Superclasses and Subclasses protected Members Relationship between Superclasses and Subclasses Case Study: Three-Level Inheritance Hierarchy Constructors and Finalizers in Subclasses Software Engineering with Inheritance Object Class

.

1

2

5.1

Introduction

• Inheritance – Software reusability – Create new class from existing class • Absorb existing class’s data and behaviors • Enhance with new capabilities

– Subclass extends superclass • Subclass – More specialized group of objects – Behaviors inherited from superclass • Can customize – Additional behaviors

.

3

5.1

Introduction

• Class hierarchy – Direct superclass • Inherited explicitly (one level up hierarchy)

– Indirect superclass • Inherited two or more levels up hierarchy

– Single inheritance • Inherits from one superclass

– Multiple inheritance • Inherits from multiple superclasses – Java does not support multiple inheritance

.

4

5.1

Introduction

• Abstraction – Focus on commonalities among objects in system

• “is-a” vs. “has-a” – “is-a” • Inheritance • subclass object treated as superclass object • Example: Car is a vehicle – Vehicle properties/behaviors also car properties/behaviors

– “has-a” • Composition • Object contains one or more objects of other classes as members • Example: Car has a steering wheel .

5

5.2 Superclasses and Subclasses • Superclasses and subclasses – Object of one class “is an” object of another class • Example: Rectangle is quadrilateral. – Class Rectangle inherits from class Quadrilateral – Quadrilateral: superclass – Rectangle: subclass

– Superclass typically represents larger set of objects than subclasses • Example: – superclass: Vehicle • Cars, trucks, boats, bicycles, … – subclass: Car • Smaller, more-specific subset of vehicles

.

6

5.2 Superclasses and Subclasses (Cont.) • Inheritance examples Superclass Student

Subclasses GraduateStudent, UndergraduateStudent Shape Circle, Triangle, Rectangle Loan CarLoan, HomeImprovementLoan, MortgageLoan Employee Faculty, Staff BankAccount CheckingAccount, SavingsAccount Fig. 5.1 Inheritance examples.

.

7

UML – Hierarchy Structure of Classes Student

Bachelor

FullTime

Magister

PartTime

.

FullTime

PhD_Student

PartTime

8

5.2 Superclasses and Subclasses (Cont.) • Inheritance hierarchy – Inheritance relationships: tree-like hierarchy structure – Each class becomes • superclass – Supply data/behaviors to other classes OR • subclass – Inherit data/behaviors from other classes

.

9

5.2 SuperClasses and SubClasses • One of the problem with inheritance is that a class can also inherit methods that it does not need. • Subclass often needs to correct inherited method. In that cases subclass simply override method of superclass by its implementation.

.

10

UML Class Diagram O b je c t

C o m m is s io n E m p lo y e e -firs tN a m e -la s tN a m e -s s n -g ro s s S a le s -c o m m is s io n R a te

B a s e P lu s C o m m is s io n E m p lo y e e -b a s e S a la ry

.

// CommissionEmployee class represents a commission employee. employee. public class CommissionEmployee extends Object { private String firstName; firstName; private String lastName; lastName; private String socialSecurityNumber; socialSecurityNumber; private double grossSales; grossSales; // gross weekly sales private double commissionRate; commissionRate; // commission percentage // fivefive-argument constructor public CommissionEmployee( CommissionEmployee( String first, first, String last, last, String ssn, ssn, double sales, sales, double rate ) { // implicit call to Object constructor occurs here firstName = first; first; lastName = last; last; socialSecurityNumber = ssn; ssn; setGrossSales( setGrossSales( sales ); // validate and store gross sales setCommissionRate( setCommissionRate( rate ); // validate and store commission rate } // end fivefive-argument CommissionEmployee constructor // set first name public void setFirstName( setFirstName( String first ) { firstName = first; first; } // end method setFirstName

Outline

// return first name public String getFirstName() getFirstName() { return firstName; firstName; } // end method getFirstName // set last name public void setLastName( setLastName( String last ) { lastName = last; last; } // end method setLastName // return last name public String getLastName() getLastName() { return lastName; lastName; } // end method getLastName // set social security number public void setSocialSecurityNumber( setSocialSecurityNumber( String ssn ) { socialSecurityNumber = ssn; ssn; // should validate } // end method setSocialSecurityNumber // return social security number public String getSocialSecurityNumber() getSocialSecurityNumber() { return socialSecurityNumber; socialSecurityNumber; } // end method getSocialSecurityNumber

Outline

// set commission employee's employee's gross sales amount public void setGrossSales( setGrossSales( double sales ) { grossSales = ( sales < 0.0 ) ? 0.0 : sales; sales; } // end method setGrossSales // return commission employee's employee's gross sales amount public double getGrossSales() getGrossSales() { return grossSales; grossSales; } // end method getGrossSales // set commission employee's employee's rate public void setCommissionRate( setCommissionRate( double rate ) { commissionRate = ( rate > 0.0 && rate < 1.0 ) ? rate : 0.0; } // end method setCommissionRate // return commission employee's employee's rate public double getCommissionRate() getCommissionRate() { return commissionRate; commissionRate; } // end method getCommissionRate // calculate commission employee's employee's pay public double earnings() earnings() { return commissionRate * grossSales; grossSales; } // end method earnings

Outline

// return String representation of CommissionEmployee object public String toString() toString() { return String.format( String.format( "%s: %s %s %s\n%s: n%s: %s %s\n%s: n%s: %.2f\ %.2f\n%s: %.2f", "commission employee", firstName, lastName, "social security number", socialSecurityNumber, "gross sales", grossSales, "commission rate", commissionRate ); } // end method toString } // end class CommissionEmployee

Outline

// BasePlusCommissionEmployee2 inherits from class CommissionEmployee. CommissionEmployee. public class BasePlusCommissionEmployee2 extends CommissionEmployee { private double baseSalary; baseSalary; // base salary per week // sixsix-argument constructor public BasePlusCommissionEmployee2( String first, first, String last, last, String ssn, ssn, double sales, sales, double rate, rate, double salary ) { // explicit call to superclass CommissionEmployee constructor super( first, first, last, last, ssn, ssn, sales, sales, rate ); setBaseSalary( setBaseSalary( salary ); // validate and store base salary } // end sixsix-argument BasePlusCommissionEmployee2 constructor // set base salary public void setBaseSalary( setBaseSalary( double salary ) { baseSalary = ( salary < 0.0 ) ? 0.0 : salary; salary; } // end method setBaseSalary // return base salary public double getBaseSalary() { return baseSalary; baseSalary; } // end method getBaseSalary

Outline

// calculate earnings public double earnings() { // not allowed: commissionRate and grossSales private in superclass return baseSalary + ( commissionRate * grossSales ); } // end method earnings // return String representation of BasePlusCommissionEmployee2 BasePlusCommissionEmployee2 public String toString() toString() { // not allowed: attempts to access private superclass members return String.format( String.format( "%s: %s %s %s\n%s: n%s: %s %s\n%s: n%s: %.2f\ %.2f\n%s: %.2f\ %.2f\n%s: %.2f", "base"base-salaried commission employee", firstName, firstName, lastName, lastName, "social security number", socialSecurityNumber, socialSecurityNumber, "gross sales", grossSales, grossSales, "commission rate", commissionRate, commissionRate, "base salary", baseSalary ); } // end method toString } // end class BasePlusCommissionEmployee2

Outline

17

5.3 protected Members • protected access – Intermediate level of protection between public and private – protected members accessible to • superclass members • subclass members • Class members in the same package

– Subclass access superclass member • Keyword super and a dot (.)

.

// CommissionEmployee class represents a commission employee. employee. public class { protected protected protected protected protected

CommissionEmployee extends Object String String String double double

firstName; firstName; lastName; lastName; socialSecurityNumber; socialSecurityNumber; grossSales; grossSales; // gross weekly sales commissionRate; commissionRate; // commission percentage

// fivefive-argument constructor public CommissionEmployee( CommissionEmployee( String first, first, String last, last, String ssn, ssn, double sales, sales, double rate ) { // implicit call to Object constructor occurs here firstName = first; first; lastName = last; last; socialSecurityNumber = ssn; ssn; setGrossSales( setGrossSales( sales ); // validate and store gross sales setCommissionRate( setCommissionRate( rate ); // validate and store commission rate } // end fivefive-argument CommissionEmployee constructor // set first name public void setFirstName( setFirstName( String first ) { firstName = first; first; } // end method setFirstName

Outline

5.4

Relationship between Superclasses and Subclasses (Cont.)

• Using protected instance variables – Advantages • subclasses can modify values directly • Slight increase in performance – Avoid set/get function call overhead

– Disadvantages • No validity checking – subclass can assign illegal value • Implementation dependent – subclass methods more likely dependent on superclass implementation – superclass implementation changes may result in subclass modifications • Fragile (brittle) software .

19

5.4

Relationship between Superclasses and Subclasses (Cont.)

• Solution of the problem – leave CommissionEmployee with private data attribute modifier – in all subclasses use method to access data attributes of superclass – use pseudovariable super in case to call superclass metohd

.

20

public class BasePlusCommissionEmployee4 extends CommissionEmployee3 { private double baseSalary; baseSalary; // base salary per week // sixsix-argument constructor public BasePlusCommissionEmployee4( String first, first, String last, last, String ssn, ssn, double sales, sales, double rate, rate, double salary ) { super( first, first, last, last, ssn, ssn, sales, sales, rate ); setBaseSalary( setBaseSalary( salary ); // validate and store base salary } // end sixsix-argument BasePlusCommissionEmployee4 constructor // set base salary public void setBaseSalary( setBaseSalary( double salary ) { baseSalary = ( salary < 0.0 ) ? 0.0 : salary; salary; } // end method setBaseSalary // return base salary public double getBaseSalary() { return baseSalary; baseSalary; } // end method getBaseSalary // calculate earnings public double earnings() earnings() { return getBaseSalary() + super.earnings super.earnings(); earnings(); } // end method earnings

Outline

// return String representation of BasePlusCommissionEmployee4 public String toString() toString() { return String. String.format( format( "%s %s\ %s\n%s: %.2f", "base"base-salaried", salaried", super.toString super.toString(), toString(), "base salary", salary", getBaseSalary() ); } // end method toString } // end class BasePlusCommissionEmployee4

Outline

public class BasePlusCommissionEmployeeTest4 { public static void main( main( String args[] args[] ) { // instantiate BasePlusCommissionEmployee4 object BasePlusCommissionEmployee4 employee = new BasePlusCommissionEmployee4( "Bob", "Lewis "Lewis", Lewis", "333"333-3333-3333", 5000, .04, 300 ); // get basebase-salaried commission employee data System. System.out. out.println( println( "Employee information obtained by get methods: methods: \n" ); System. System.out. out.printf( printf( "%s %s\ %s\n", "First "First name is", is", employee. employee.getFirstName() getFirstName() ); System. System.out. out.printf( printf( "%s %s\ %s\n", "Last "Last name is", is", employee. employee.getLastName() getLastName() ); System. System.out. out.printf( printf( "%s %s\ %s\n", "Social "Social security number is", is", employee. employee.getSocialSecurityNumber() getSocialSecurityNumber() ); System. System.out. out.printf( printf( "%s %.2f\ %.2f\n", "Gross sales is", is", employee. employee.getGrossSales() getGrossSales() ); System. System.out. out.printf( printf( "%s %.2f\ %.2f\n", "Commission "Commission rate is", is", employee. employee.getCommissionRate() getCommissionRate() ); System. System.out. out.printf( printf( "%s %.2f\ %.2f\n", "Base salary is", is", employee.getBaseSalary() employee.getBaseSalary() );

Outline

employee. employee.setBaseSalary( setBaseSalary( 1000 ); // set base salary System. System.out. out.printf( printf( "\ "\n%s:\ n%s:\n\n%s\ n%s\n", "Updated employee information obtained by toString", toString", employee. employee.toString() toString() ); } // end main } // end class BasePlusCommissionEmployeeTest4

Outline

Employee information obtained by get methods: First name is Bob Last name is Lewis Social security number is 333333-3333-3333 Gross sales is 5000,00 Commission rate is 0,04 Base salary is 300,00 Updated employee information obtained by toString: toString: basebase-salaried commission employee: Bob Lewis social security number: 333333-3333-3333 gross sales: 5000,00 commission rate: 0,04 base salary: 1000,00

Outline

26

5.4 Ticket Reservation Example • Travel agency handles with reservation of several kinds • Superclass Reservation connecter via composition with Calendar class (Date) and via aggregation with Customer – class Person • Subclasses of the Reservation class are TrainReservation class and FlightReservation class

.

27

5.4 `Ticket Reservation Example • Class Reservation: – date – customer

• methods: – print – toString

.

5.4 Ticker Reservation – UML Class Diagram

Person Calendar

1

1

Reservation +toString() +print()

1

FlightReservation

TrainReservation

-flight -seat +getFlight() +getSeat() +toString() +print()

-train -carriage -seat +getVlak() +getVagon() +getSedadlo() +toString() +tisk()

.

1

-name -sex +getName() +getSex() +toString() +print()

28

import java. java.util. util.Calendar; Calendar; class Person { private String name; name; private String sex; public Person() Person() { super(); name="neuvedeno"; name="neuvedeno"; sex="neuvedeno"; } public Person( Person(String name, name, String sex) { this. this.name = name; name; this.sex= this.sex= sex; } public String toString() toString() { return String. String.format(" format(" %s: %s %s: %s \n", "name", name",name ",name,"sex",sex); name,"sex",sex); } public void tisk() { System. System.out. out.println( println(this. this.getClass(). getClass().getName ().getName()+ getName()+this ()+this. this.toString()); toString()); } public String getName() getName() { return name; name; } public String getSex getSex() () { return sex; } }

Outline

public class Reservation { public Reservation( Reservation(Calendar d){ date = d; } Calendar date; date; Person customer; customer; public void setCustomer( setCustomer(Person o){ customer = o; } public Person getCustomer(){ getCustomer(){ return customer; customer; } public String toString(){ toString(){ return String. String.format(" format("customer ("customer: customer: %sDate %sDate: sDate: %tF %tF", tF", customer. customer.toString(), toString(), date); date); } public void print(){ print(){ System. System.out. out.print( print(this. this.toString()); toString()); } }

Outline

import java. java.util. util.Calendar; Calendar; public class TrainReservation extends Reservation { String train; train; int carriage; carriage; int seat seat; public TrainReservation( TrainReservation(Calendar d, String v, int vg, vg, int s){ super(d); train = v; carriage = vg; vg; seat seat = s; } public String getTrain getTrain(){ Train(){ return train; train; } public int getCarriage getCarriage(){ Carriage(){ return carriage; carriage; } public int getSeat getSeat(){ return seat seat; } public String toString(){ toString(){ return String. String.format("%s format("%s\ ("%s\nTrain: Train: %s carriage: carriage: %4d, seat seat: %3d\ %3d\n" ,super.toString ,super.toString(),vlak, toString(),vlak, carriage, carriage, seat seat); } public void print(){ print(){ System. System.out. out.println( println(this. this.toString()); toString()); } }

Outline

import java. java.util. util.Calendar; Calendar; public class FlightReservation extends Reservation { public FlightReservation( FlightReservation(Calendar d, String l, String s){ super(d); flight = l; seat = s; } String flight; flight; String seat; seat; public String getFlight(){ getFlight(){ return flight; flight; } public String getSeat(){ getSeat(){ return seat; seat; } public String toString(){ toString(){ return String. String.format("%s format("%s \nFlight: nFlight: %s seat: seat: %s\ %s\n", super.toString super.toString(), toString(),getFlight (),getFlight(), getFlight(),getSeat (),getSeat()); getSeat()); } public void print(){ print(){ System. System.out. out.println( println(this. this.toString()); toString()); } }

Outline

import java java. .util. util.Calendar; Calendar; public class Re Reservation servationTest servationTest { public static void main( main(String[] String[] args) args) { TrainReservation v = new TrainReservation( TrainReservation(Calendar. Calendar.getInstance(), getInstance(), "Pendolino",506,28); Pendolino",506,28); Person o = new Person("Adam","m Person("Adam","man ("Adam","man"); an"); v.setCustomer v.setCustomer(o); setCustomer(o); FlightReservation f = new FlightReservation( FlightReservation(Calendar. Calendar.getInstance(), getInstance(), "Ok 225","14A"); o = new Person("Alena", Person("Alena",“ ("Alena",“woman"); woman"); f.setCustomer f.setCustomer(o); setCustomer(o); v.print v.print(); print(); f.print f.print(); print(); System. System.out. out.println(" println("Flight ("Flight: Flight: "+f.flight "+f.flight); flight); //failed //failed access - proper access to superclass attributes // only through access method //System //System. System.out. out.println(" println("Customer ("Customer name: name: "+f.customer "+f.customer. customer.name); name); //correct //correct System. System.out. out.println(" println("NAme ("NAme of customer: customer:“ +f.getCustomer +f.getCustomer(). getCustomer().getName ().getName()+" getName()+"\ ()+"\n");

Outline

// qualification of the r variable Reservation r; r = v; r.print r.print(); print(); r = f; r.print r.print(); print(); System. System.out. out.println(" println("Name "+r.getCustomer(). ("Name: Name: "+r.getCustomer getCustomer().getName ().getName()+ getName()+ " sex: sex: "+r.getCustomer "+r.getCustomer(). getCustomer().getSex ().getSex()); getSex()); //the //the method getLet() getLet() is undefined for the type Reservation; Reservation; //System //System. System.out. out.println( println(“Flight: Flight: "+r.get "+r.getFlight getFlight()); Flight());

FlightReservation fr; fr; fr = (FlightReservation (FlightReservation) FlightReservation) r; System. System.out. out.println( println(“Flight: Flight: "+fr "+fr. fr.getFlight()); getFlight()); } }

Outline

Customer: name: Adam sex: man Date: 20062006-1111-12 Train: Pendolino carriage: 506, seat: Customer: name: Alena sex: woman Date: 20062006-1111-12 Flight: Ok 225 seat: 14A

Outline 28

Flight: Ok 225 Name of customer: Alena Customer: name: Adam sex: man Date: 20062006-1111-12 Train: Pendolino carriage: 506, seat: Customer: name: Alena sex: woman Date: 20062006-1111-12 Flight: Ok 225 seat: 14A Name: Alena sex: woman Flight: Ok 225

28

5.6

Constructors and Finalizers in Subclasses

• Instantiating subclass object – Chain of constructor calls • subclass constructor invokes superclass constructor – Implicitly or explicitly • Base of inheritance hierarchy – Last constructor called in chain is Object’s constructor – Original subclass constructor’s body finishes executing last – Example: FlightReservation/Reservation/Object hierarchy • Reservation constructor called second last (last is Object constructor) • Reservation constructor’s body finishes execution second (first is Object constructor’s body) .

36

5.6

Constructors and Destructors in Derived Classes

• Garbage collecting subclass object – Chain of finalize method calls • Reverse order of constructor chain • Finalizer of subclass called first • Finalizer of next superclass up hierarchy next – Continue up hierarchy until final superreached • After final superclass (Object) finalizer, object removed from memory

.

37

38

5.7

Software Engineering with Inheritance

• Customizing existing software – Inherit from existing classes • Include additional members • Redefine superclass members • No direct access to superclass’s source code – Link to object code

– Independent software vendors (ISVs) • Develop proprietary code for sale/license – Available in object-code format • Users derive new classes – Without accessing ISV proprietary source code

.

39

5.8 Object Class • Highest class in the class hierarchy • provide some essential methods (see following table) • used for highest qualification of the instances i.e. stored in lists

.

40

5.8 Object Class Method

Description

clone

This protected method, which takes no argunemts and returns an Object reference, makes a copy of the object on which it is called. When cloning is required for objects of a class, the class should override method clone as a public method and should implement interface Clonable (package java.lang). The default implementation of this method provide a so-called shallow copy.

equals

This method compares two objects for equality and returns true if they are equal and false otherwise. The method takes any Object as an argument. When objects of a particular class must be compared for equality, the class should override method equals to compare the contents of the two objects. i.e. object1.equals(object2) .

41

5.8 Object Class Method

Description

finalize

The protected method is called by the garbage collector to perform termination housekeeping on an object just before the garbage collector reclaims the object’s memory.

getClass

Every object in Java knows its own type at execution time. Method getClass returns an object of class Class. To obtain string representation of return value of this method we must still use getName method.

.

42

5.8 Object Class Method

Description

hashCode A hashtable is a data structure that relates one object, called the key, to another object, called the value. When initially inserting a value into a hashtable, the key’s hashCode method is called. The hashcode value returned is used by the hashtable to determine the location at which to insert the corresponding value. The key’s hashcode is also used by the hashtable to locate the key’s corresponding value. notify wait notifyAll

These methods and the three overloaded versions of wait methods are related to multithreading.

toString

This method returns a String representation of an object. The default implementation of this method returns the package name and class name of the object’s class followed by a hexadecimal representation of the value returned by the object’s hashcode method. .