1 / 57

Inheritance Review

Inheritance Review. Inheritance, Overriding, and Polymorphism. Topics. Inheritance Polymorphism . Class hierarchies. _______ ANIMAL________ / MAMMAL REPTILE / /

miette
Download Presentation

Inheritance Review

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. Inheritance Review Inheritance, Overriding, and Polymorphism

  2. Topics • Inheritance • Polymorphism

  3. Class hierarchies _______ ANIMAL________ / \ MAMMAL REPTILE / \ / \ WHALE DOG SNAKE LIZARD / \ IGUANA SKINK It's common/natural for classes to be related to each other

  4. Subclasses and Superclasses _______ ANIMAL________ / \ MAMMAL REPTILE / \ / \ WHALE DOG SNAKE LIZARD / \ IGUANA SKINK Class hierarchies represent "IS A" (or "is kind of") relationships.

  5. Why Capture these "is a kind of" relationships? • Better organize related concepts • Reduce duplication through inheritance Advantages?

  6. So what is inheritance? • the key of object-oriented programming. • is the act of sharing state and behaviour from a more general type of class (i.e. a superclass). • allows code to be shared between classes (software reusability). • saves time when programming (less code needs to be written). • encourages reuse of well designed objects (i.e., proven and tested code). • helps keep code simple.

  7. A subclass: • Is a class that does the inheriting by using state (i.e. instance variables) and behaviour (i.e., methods) from some other class. • Note: it cannot access private methods or instance variables from its superclasses.

  8. A superclass • Is a class from which its subclasses inherit state and behaviour. • Is more general that its subclasses. • Note: subclasses are more specific and "larger".

  9. A direct superclass: • is the superclass from which the subclass explicitly inherits. • Example • Mammal is the direct superclass of Dog _______ ANIMAL________ / \ MAMMAL REPTILE / \ / \ WHALE DOG SNAKE LIZARD / \ IGUANA SKINK

  10. Example _______ ANIMAL________ / \ MAMMAL REPTILE / \ / \ WHALE DOG SNAKE LIZARD / \ IGUANA SKINK class Animal {…} class Mammal extends Animal {…} class Reptile extends Animal {…} class Whale extends Mammal {…} class Dog extends Mammal {…} class Snake extends Reptile {…} class Lizard extends Reptile {…} class Iguana extends Lizard {…} class Skink extends Lizard {…}

  11. Example _______ ANIMAL________ / \ MAMMAL REPTILE / \ / \ WHALE DOG SNAKE LIZARD / \ IGUANA SKINK class Animal { public int age; public getAge(){ return age}; } class Mammal extends Animal { public float bodyTemperature; public get bodyTemperature{return bodyTemperature} class Dog extends Mammal { String name; …} fido.getAge()

  12. Instance Method lookup • When a message (method) is sent to an instance, Java must look up the method in the class hierarchy. • If Java does not find the method defined in the class of the receiver, it checks the superclass. • If not found their either, it checks the superclass of that class and so on ... until the Object class is reached. • This lookup occurs at runtime (i.e. when the program is executing).

  13. Class Method Inheritance • For class methods, the look-up occurs at compile time. • Since an inherited class method is compiled as static (i.e., lookup at compile time) then within that method the object must be treated as an instance of the class that defines the method, not the subclass that inherits it.

  14. How many classes can a class inherit from? _______ ANIMAL________ / \ MAMMALPET REPTILE / \/ / \ WHALE DOG SNAKE LIZARD / \ IGUANA SKINK Is a dog both a Mammal and a Pet?

  15. Multiple Inheritance • is the term given to a class that inherits from more than one direct superclass. • is NOT supported in Java (but it is in C++ which we will not talk about at all). • can get some of its advantages through the notion of interfaces.

  16. Exercise All vehicles have a name, speed, maximum speed, and operator. Passenger vehicles have a maximum passenger capacity and lists of passengers, while cargo vehicles have a maximum load capacity and a current load. Busses have a school district they serve, while planes have a list of airports they serve. Both operators and passengers are people. Define the basic class structure for this problem in Java and make sure it compiles.

  17. Exercise All vehicles have a name, speed, maximum speed, and operator. Passenger vehicles have a maximum passenger capacity and lists of passengers, while cargo vehicles have a maximum load capacity and a current load. Busses have a school district they serve, while planes have a list of airports they serve. Both operators and passengers are people. Define the basic class structure for this problem in Java and make sure it compiles. Answer: Vehicle.java

  18. Exercise A university has students, faculty, staff and administrators. Each has a number, name and date of birth. Faculty teach courses that have numbers, names and enrollment. Courses are given in rooms at specific times. Rooms have room numbers and capacities. Faculty and staff and administrators are employees. Employees have social security numbers and levels. Staff are either clerical or technical. Dalhousie, Carleton and Western are universities. All employees get salaries. Faculty have research grants that other employees and staff do not. Define the basic class structure for this problem in Java and make sure it compiles.

  19. Is a class without instances useful? Human / \ Female Male Should we make instances of Human?

  20. An Abstract Class • is a class that can never be instantiated (i.e., never have instances). • always has subclasses • helps to organize a program

  21. A Concrete Class • is a class that can be instantiated (i.e., can have instances).

  22. More Visibility Modifiers Others modifiers: public, private, static

  23. Recall: the other modifiers

  24. Modifier Summary

  25. Rules of thumb • Use public only for methods and constants that form part of the API of the class. • Use protected for fields and methods that aren’t necessary to "use" in the class, but may be of interest to anyone creating a subclass as part of a different package

  26. Rules of thumb • Use none (ie. The defualt package visability) for fields ant methods that you want hidden outside the package , but which you want cooperating classes within the same package to have access to. • Use private for fields and methods that are only used inside the class and should be hidden elsewhere.

  27. Examples hierarchies Student GraduateStudent UndergraduateStudent Shape Circle Triangle Rectangle Square Loan CarLoan HomeImprovemantLoan MortgageLoan Account CheckingAccount SavingsAccount Which should be abstract? Which concrete?

  28. Are they right? Shape Circle Triangle Rectangle Square • How do we know what subclasses to use ? • What about a cube or a sphere or even a tetrahedron ?

  29. A better shape hierarchy? • Perhaps more abstract classes would help? • What else should we add? Shape TwoDimensionalShape Circle Triangle Rectangle Square ThreeDimensionalShape Sphere Cube Tetrahedron

  30. More extensive yet • What should be abstract? Shape TwoDimensionalShape Ellipse Circle Polygon Triangle Rectangle Square ThreeDimensionalShape Sphere Polyhedron Cube Tetrahedron

  31. Can we enforce the idea of an abstract class? • Yes, just use the abstract keyword: • Syntax: public abstract class TheSubclassName extends TheSuperclassName{ ... }

  32. Every object inherits from something!!! • When we do not write the extends portion of the declaration, Java automatically makes the class a subclass of Object • Object is the most general class (as everything inherits from).

  33. Dogs bark, Terriers yap Mammal May need to override The definition of a method!! Dog Terrier fido max

  34. Overriding • is used when a method belonging to a superclass is not needed or is inappropriate • allows the re-writing of the method for use in the subclass only • the subclass own method with the same name (and same parameter list) that does something else (perhaps nothing).

  35. Example Person (name, phone#, address) Employee (employee#, workPhone#) Professor (courses, office #) Secretary (workload, schedule) Student (student#, courses, gpa) FullTimeStudent (major) PartTimeStudent (workPhone#)

  36. Class Person public class Person { protected String name, phoneNumber, address; /* Place code for methods here */ } public class Employee extends Person { protected int employeeNumber; protected String workPhoneNumber; /* Place code for methods here */ } public class Professor extends Employee { protected Vector courses; protected String officeNumber; /* Place code for methods here */ } public class Secretary extends Employee { protected Vector workLoad; protected Hashtable schedule; /* Place code for methods here */ }

  37. Class Person continued public class Student extends Person { protected int studentNumber; protected Vector courses; protected float gpa; /* Place code for methods here */ } public class FullTimeStudent extends Student { protected String major; /* Place code for methods here */ } public class PartTimeStudent extends Student { protected String workPhoneNumber; /* Place code for methods here */ }

  38. Which class gets what? Person (name, phone#, address) Employee (employee#, workPhone#) Professor (courses, office #) Secretary (workload, schedule) Student (student#, courses, gpa) • Which classes should implement • getName or getcourses methods? • What should the toString methods return?

  39. Possible toString output Person NAME: Jim Class ADDRESS: 1445 Porter St. PHONE #: 845-3232 Employee NAME: Rob Banks ADDRESS: 789 ScotiaBank Road. PHONE #: 899-2332 EMPLOYEE #: 88765 WORK #: 555-2433 Professor NAME: Guy Smart EMPLOYEE #: 65445 WORK #: 232-3415 OFFICE #: 5240 PA Secretary NAME: Earl E. Bird ADDRESS: 12 Knowhere Cres. PHONE #: 443-7854 EMPLOYEE #: 76845 WORK #: 444-3243 Student NAME: May I. Passplease ADDRESS: 5567 Java Drive PHONE #: 732-8923 STUDENT #: 156753

  40. toString for the Person class //This is the toString method for the Person class public String toString() { return("Person \n" + " NAME: " + getName() + "\n" + " ADDRESS: " + getAddress() + "\n" + " PHONE #: " + getPhoneNumer()); } Can we do better? Remember this method will be inhetited!!!

  41. A better toString for the Person class //This is the toString method for the Person class public String toString() { return(this.getClass().getName() + "\n" + " NAME: " + getName() + "\n" + " ADDRESS: " + getAddress() + "\n" + " PHONE #: " + getPhoneNumer()); }

  42. toString for the Employee class //This is the toString method for the Employee class public String toString() { return(super.toString() + "\n" + " EMPLOYEE #: " + getEmployeeNumber() + "\n" + " WORK #: " + getWorkNumer()); } Idea: super classes method PLUS!!!

  43. What next? Person Employee Professor Secretary Student Secretary NAME: Earl E. Bird ADDRESS: 12 Knowhere Cres. PHONE #: 443-7854 EMPLOYEE #: 76845 WORK #: 444-3243 Student NAME: May I. Passplease ADDRESS: 5567 Java Drive PHONE #: 732-8923 STUDENT #: 156753 Person NAME: Jim Class ADDRESS: 1445 Porter St. PHONE #: 845-3232 Employee NAME: Rob Banks ADDRESS: 789 ScotiaBank Road. PHONE #: 899-2332 EMPLOYEE #: 88765 WORK #: 555-2433 Professor NAME: Guy Smart EMPLOYEE #: 65445 WORK #: 232-3415 OFFICE #: 5240 PA

  44. toString for the Professor class //This is the toString method for the Professor class public String toString() { return(this.getClass().getName() + "\n" + " NAME: " + getName() + "\n" + " EMPLOYEE #: " + getEmployeeNumber() + "\n" + " WORK #: " + getWorkNumer()); " OFFICE# : " + getOfficeNumber() + "\n"); }

  45. toString for the Student class • inherits from Person and also displays the student number. //This is the toString method for the Student class public String toString() { return(super.toString() + "\n" + " STUDENT# : " + getStudentNumber() + "\n"); }

  46. Inheritance with Constructors • A subclass automatically inherits the constructor of its superclass • Good programming style: override the superclass constructor • should explicitly call the superclass constructor at the beginning of code • If not called explicitly, a superclass constructor is automatically called at the beginning of the subclass constructor

  47. Person constructors public class Person { protected String name, phoneNumber, address; public Person() { setName(""); setPhoneNumber(""); setAddress("") } public Person(String aName, String aPhoneNumber, String anAddress) { setName(aName); setPhoneNumber(aPhoneNumber); setAddress(anAddress); } }

  48. Employee Constructors public class Employee extends Person { protected int employeeNumber; protected String workPhoneNumber; public Employee() { //There is an implicit call to the Person() constructor here setEmployeeNumber(0); setWorkPhoneNumber(""); } public Employee(int aNumber, String aPhoneNumber) { //There is an implicit call to the Person() constructor here setEmployeeNumber(aNumber); setWorkPhoneNumber(aPhoneNumber); } }

  49. Professor Constructors public class Professor extends Employee { protected Vector courses; protected String officeNumber; public Professor() { super(); courses = new Vector(); setOfficeNumber(""); } public Professor(int aNumber, String aPhoneNumber, String anOfficeNumber) { super(aNumber, aPhoneNumber); courses = new Vector(); setOfficeNumber(anOfficeNumber); } }

  50. Final • When a method is declared as final, it is not allowed to be overridden by a subclass. • If a class is declared final, it cannot have subclasses.

More Related