Chapter 6 Class Hierarchies, Inheritance, and Interfaces This is a very good chapter for us at this...
-
date post
21-Dec-2015 -
Category
Documents
-
view
216 -
download
0
Transcript of Chapter 6 Class Hierarchies, Inheritance, and Interfaces This is a very good chapter for us at this...
Chapter 6 Class Hierarchies, Inheritance, and Interfaces
This is a very good chapter for us at this point in time.
We have been programming hard this semester and know how to use most java programming commands.
Now we will take a look at inheritance. Some areas that I have been making you
address in your programs and now we will look at these things again.
I want to thank you for all your hard work thus far this semester.
Chapter 6
Object Oriented design Abstraction Encapsulation Polymorphism Inheritance
Modular programming Inheritance, polymorphism, and
interfaces
6.1 Class Hierarchies and Inheritance
Extending existing classes New class is called subclass
can add data fields and methods can override existing methods
Original class is called Super Class See example page 360 Hierarchical
in biology
is a versus has a
a car is a vehicle car is subclass of vehicle
a car has a wheel attribute of car
Not all vehicles have wheels Snowmobile
public class Car extends Vehicle {Wheels[ ] w = new Wheels[4]
Keyword extends makes car subclass of vehicle
Case study: Hierarchy employee class
Class called NewEmployee stores basic employee data name SSN job title address phone number age start date total pay to date
Methods
Besides standard methods (accessor, modifiers….
Also methods to compute numbers of years with
company years to retirement update total pay
What if you need to differentiate between hourly and salaried
Analysis and Design
See tables page 362 Now what do we need to do to add
SalaryEmployee HourlyEmployee
We inherit from NewEmployee then add necessary methods and
attributes See tables on pages 363 and 364
Implementation
See pages 364-366 for definition of base class See attributes page 364 Notice use of this. page 365 Notice 3 constructors page 365
one default one only basic information one complete
Look at equals method bottom page 366
This used heavily
Used this to differentiate names this.name this.age
Used to call methods not typically used
New use bottom page 367 use to call constructor this(name, social);
Class SalaryEmployee
public class SalaryEmployee extends NewEmployee {
SalaryEmployee takes on all methods and attributes of superClass
So implementation on page 369 only includes the necessary additional data fields and methods
Implementation SalaryEmployee
See data field only need annualSalary
Notice constructor calls super(name, social); same for larger constructor calls the constructor of the super class
Can user super in other methods see toString
Implementation HourlyEmployee
See Pages 372 – 373
Pages 373 – 374 test app, simply tests the classes
See running code in JBuilder
Operations in Class Hierarchy Section 6.1
Object
NewEmployee
HourlyEmployeeSalaryEmployee
Design
See tables pages 377-378
Method Overloading
Each class has 3 constructor methods
Known as Overloading Java knows which to call based on
the method signature. If none found get method not found
error
Method Overriding
Each class has a toString method Which one does it call The one in the subclass overrides the
one in the superclass If none in sub class will call one in
super class allows you to override functionality of
methods in superclass if don’t like default functionality
Protected Visibility
Data fields defined as private in a super class can not be accessed in the subclass directly.
Data fields defined as protected in a super class can be accessed directly in a subclass.
Shadowing data fields
If local variable (in method) has same name as class data field. can not access class data field local field shadows it can use prefix this to access it
Same applies to data fields in super class can use prefix super to access it
Assignment in class Hierarchy
See example 6.2 page 381 See declarations first Assignments obj = anEmp
can only access methods defined in obj toString is one But will call toString of NewEmployee
Assignment in class Hierarchy
Similarly on page 382 – 383 anEmp = hourEmp anEmp was originally instantiated as
NewEmployee therefore will only have methods available
that are a part of NewEmployee When we assign within a class hierarchy
A variable of type super class can reference an object of sub class converse is not true
Casting in Class hierarchy
We can remedy not being able to access methods that are not a part of super class when made to reference sub class via casting
((HourlyEmployee) anEmp).setHours(30.0);
Need to be careful with this, if not correctly can create run time errors.
Passing Objects as arguments
When passing arguments of different class types same rules apply as for assignment
Remember that objects passed by reference
Therefore change the state of the object in a method it is changed in the calling program
instanceof Operator
object instanceof ClassName test to see whether object (instance
variable) is and instance of className (class type)
See bottom of page 387 clerk instanceof HourlyEmployee When might you use this?
Section 6.3 Polymorphism
Another aspect of Polymorphism would allow us to have an array of employee of any type.
Create an array of NewEmployee objects. can then store any object type
See methods bottom of page 389 See code page 391
notice use of instanceof in computePayroll
Dynamic binding
Notice bottom page 391 toString loop inside we have result +
employees[I].toString() java does not know which toString
method to call until run time because does not know what type of
object employees[I] refers to until run time
known as dynamic binding
6.4 Interfaces
An interface is very similar to a class It is used to specify the requirements
for a class If a class implements an interface it
must have a certain base functionality See simple example bottom page 395 Classes that implement this interface
must provide a method: public double calcWeeklyPay();
Abstract method
The class in this interface: public double calcWeeklyPay()
is an abstract method since it has no body
it is not defined in the interface, only the header this does define the signature
interfaces can only have: abstract methods constant definitions (static final)
Implements
A class can only extend on class, but can implement several interfaces
If our classes implement Payable it would simplify the use of this class
See code middle of page 396 Method to call (which calcWeeklyPay)
determined at runtime
Steps for Payable
Write Payable interface (file Payable.java)
Add implements Payable to all classes that implement it. Verify that these classes contain complete definitions for method calcWeeklyPay()
Use casting to ensure that all calls to method calcWeeklyPay() are applied only to type Payable references
Comparable interface
Java has a number of useful built in interfaces
Comparable requires those that implement interface
to provide compareTo method See table page 398 Allows us to sort Comparable objects
Sorting
Code page 399 allows sorting If employee types implements
Comparable must provide compareTo bottom page 402 allows sort by SSN
Abstract Classes 6.5
Inheritance is used to make it easier to re-use code.
Additionally inheritance is used to provide structure to groups of related classes.
A car is a vehicle and a car has a wheel A car is a subclass of vehicle A car has a data field of wheel
Case Study Page 405
Need to find the total area of a collection of geometric figures.
For instance a painter looking to find exterior area of house to purchase paint.
Would like to create an array of geometric shapes. Array must be of like data types right?
Abstract class
An abstract class provides an outline of a class. Leaves the complete definition to those
classes that extend it. Contains classes that are defined by those
classes that extend it. You can not create an instance of an
abstract class. Abstract classes put the common members
as high up in the hierarchy as possible
GeoFigure case study
Page 408 Rectangle extends GeoFigure
Defines the methods computeArea computePerimeter
Page 410 Circle extends GeoFigure Defines the methods
computeArea computePerimeter
GeoFigure case study
Page 411 Triangle extends GeoFigure
Defines the methods computeArea computePerimeter
GeoFigure case study
See implementation Page 412 Can now create an array of GeoFigure
and put in it Triangle Circle Rectangle
Since they are all of the same type
GeoFigure case study
Can put in loop and use .toString to print each type. Since each shape class properly overrode
the toString we each prints in it’s own proper format
Can put in loop and call the computeArea method to add up all the areas. Abstract class makes sure that all the
method names are the same.
Drawing figures using an Abstract class and an Interface 6.6
GeoFigure
TriangleCircle
Drawable
DrawableTriangleDrawableRectangle DarwableCircle
Rectangle
New Geofigure
Add new data fields and methods to Geofigure
See table bottom of page 415
Drawable interface
See Drawable interface top of page 416 drawMe draws the figures on the
screen
Implementation
See implementation pages 418-421
Multiple inheritance
Java does not support multiple inheritance
Multiple inheritance in when a class extends more than one superclass.
The use of multiple inheritance is and it’s appropriateness has been debated by object oriented developers.
Typical example
Toy Elephant
ToyElephant
Interfaces
Interfaces also allow for a limited form of multiple inheritance
An interface has all abstract methods
It’s data fields can only be final class data fields
A class does not extend an interface, rather it implements it.
Packages 6.7
The package to which a class belongs is declared at the top of the class. Reserved word package followed by
package name and semicolon All classes in the same package are
stored in the same directory or folder
Packages
Classes that are not a part of the package can only access the public members. Member is a data field or method defined in a
class The complete name of a class is
packageName.className See middle 425 Only need this until variable is “bound” to
the instance. Once this occurs java knows which class to use
Packages and default visibility
There is a fourth kind of visibility we have not looked at yet. default visibility also called package visibility
Visibility
Private Only by class members
Protected Only by child classes
Public Anyone
Default (none) By anyone in the package
Section 6.8 Testing a Program System
Must learn to test in stages as the program develops
Top down Testing and stubs
Use a stub when testing for all methods that are not yet complete
A stub implements the interface but the body performs some minimal basic function
Typically also displays when in stub See example middle page 428
Bottom up testing and drivers
As method is completed it is substituted for it’s stub
Before putting new method in class we typically preliminarily test it with a driver.
Simple program to test a class has small main that instantiates object then calls the methods
Bottom up testing and drivers
These drivers are typically inserted directly in the class That is the class includes a main
method that is only used when testing the class
called bottom-up testing these can then be used to test the class
whenever changes are made allows for keeping previous tests made
Testing techniques
Black box versus White box testing will cover this heavily in software
engineering class black-box
tester has no knowledge of the code being tested
verifies that system meets the specifications white-box (or glass-box)
tester has knowledge of the code develops tests to test all the code
for instance all branches in an if statement
Common Programming Errors
Be VERY conservative with visibility of data fields all remain private except is very good
reason not to Can use this and super to call
constructors