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.

Slides:



Advertisements
Similar presentations
Final and Abstract Classes
Advertisements

Module 8 “Polymorphism and Inheritance”. Outline Understanding Inheritance Inheritance Diagrams Constructors in Derived Classes Type Compatibility Polymorphism.
CS 106 Introduction to Computer Science I 04 / 11 / 2008 Instructor: Michael Eckmann.
Inheritance Inheritance Reserved word protected Reserved word super
Inheritance Java permits you to use your user defined classes to create programs using inheritance.
ACM/JETT Workshop - August 4-5, :Inheritance and Interfaces.
ITEC200 – Week03 Inheritance and Class Hierarchies.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 Chapter 12 More OOP, Interfaces, and Inner Classes.
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,
INF 523Q Chapter 7: Inheritance. 2 Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3.
CS 106 Introduction to Computer Science I 04 / 16 / 2010 Instructor: Michael Eckmann.
Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3.
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
CS 106 Introduction to Computer Science I 11 / 15 / 2006 Instructor: Michael Eckmann.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter N - 1 Chapter 13 Polymorphism is-a relationships Interfaces.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Chapter 10 Classes Continued
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter N - 1 Chapter 13 Polymorphism is-a relationships Interfaces.
Chapter 7 - Generalization/Specialization and Inheritance1 Chapter 7 Generalization/Specialization and Inheritance.
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
CISC6795: Spring Object-Oriented Programming: Polymorphism.
1 Understanding Inheritance COSC 156 C++ Programming Lecture 8.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Chapter 11 Inheritance and Composition. Chapter Objectives Learn about inheritance Learn about subclasses and superclasses Explore how to override the.
Inheritance and Class Hierarchies Ellen Walker CPSC 201 Data Structures Hiram College.
1 Java Inheritance. 2 Inheritance On the surface, inheritance is a code re-use issue. –we can extend code that is already written in a manageable manner.
Features of Object Oriented Programming Lec.4. ABSTRACTION AND ENCAPSULATION Computer programs can be very complex, perhaps the most complicated artifact.
APCS Java AB 2004 Review of CS1 and CS2 Review for AP test #1 Sources: 2003 Workshop notes from Chris Nevison (Colgate University) AP Study Guide to go.
Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms Inheritance and Polymorphism.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
More on Hierarchies 1. When an object of a subclass is instantiated, is memory allocated for only the data members of the subclass or also for the members.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
 All calls to method toString and earnings are resolved at execution time, based on the type of the object to which currentEmployee refers.  Known as.
Summing Up Object Oriented Design. Four Major Components: Abstraction modeling real-life entities by essential information only Encapsulation clustering.
8. Inheritance “Is-a” Relationship. Topics Creating Subclasses Overriding Methods Class Hierarchies Abstract Class Inheritance and GUIs The Timer Class.
Inheritance and Access Control CS 162 (Summer 2009)
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
Object Oriented Programming
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
 Pearson Education, Inc. All rights reserved Object-Oriented Programming: Polymorphism.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Coming up: Inheritance
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
Classes, Interfaces and Packages
Java Software Solutions Lewis and Loftus Chapter 8 Copyright 1997 by John Lewis and William Loftus. All rights reserved. 1 Inheritance -- Introduction.
1 / 71 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 4 Programming Fundamentals using Java 1.
1 Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Author: DoanNX Time: 45’.  OOP concepts  OOP in Java.
Inheritance a subclass extends the functionality of a superclass a subclass inherits all the functionality of a superclass don't reinvent the wheel – "stand.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Modern Programming Tools And Techniques-I
Inheritance and Polymorphism
Understanding Inheritance
Object-Oriented Programming: Polymorphism
Java Programming Language
Advanced Java Programming
Java Inheritance.
Final and Abstract Classes
Presentation transcript:

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

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 DrawableTriangle DrawableRectangle 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

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 ToyElephant 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