1 / 55

Chapter 6 Class Hierarchies, Inheritance, and Interfaces

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.

ronalee
Download Presentation

Chapter 6 Class Hierarchies, Inheritance, and Interfaces

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

  2. Chapter 6 • Object Oriented design • Abstraction • Encapsulation • Polymorphism • Inheritance • Modular programming • Inheritance, polymorphism, and interfaces

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

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

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

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

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

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

  9. 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);

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

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

  12. Implementation HourlyEmployee • See Pages 372 – 373 • Pages 373 – 374 test app, simply tests the classes • See running code in JBuilder

  13. Operations in Class Hierarchy Section 6.1 Object NewEmployee SalaryEmployee HourlyEmployee

  14. Design • See tables pages 377-378

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

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

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

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

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

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

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

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

  23. 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?

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

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

  26. 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();

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

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

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

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

  31. Sorting • Code page 399 allows sorting • If employee types implements Comparable • must provide compareTo • bottom page 402 allows sort by SSN

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

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

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

  35. GeoFigure case study • Page 408 Rectangle extends GeoFigure • Defines the methods • computeArea • computePerimeter • Page 410 Circle extends GeoFigure • Defines the methods • computeArea • computePerimeter

  36. GeoFigure case study • Page 411 Triangle extends GeoFigure • Defines the methods • computeArea • computePerimeter

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

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

  39. Drawing figures using an Abstract class and an Interface 6.6 GeoFigure Circle Triangle Rectangle Drawable DrawableTriangle DrawableRectangle DarwableCircle

  40. New Geofigure • Add new data fields and methods to Geofigure • See table bottom of page 415

  41. Drawable interface • See Drawable interface top of page 416 • drawMe draws the figures on the screen

  42. Implementation • See implementation pages 418-421

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

  44. Typical example Toy Elephant ToyElephant

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

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

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

  48. Packages and default visibility • There is a fourth kind of visibility we have not looked at yet. • default visibility • also called package visibility

  49. Visibility • Private • Only by class members • Protected • Only by child classes • Public • Anyone • Default (none) • By anyone in the package

  50. Section 6.8 Testing a Program System • Must learn to test in stages as the program develops

More Related