1 / 32

Inheritance

Inheritance. Chapter 8. Inheritance. Superclass. subclass of Animal superclass of dog and cat. Subclass. Superclass has its own fields and methods. Subclass inherits all of superclass fields and methods and adds some of its own. Subclass has its own fields and methods.

dexter
Download Presentation

Inheritance

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

  2. Inheritance Superclass subclass of Animal superclass of dog and cat Subclass

  3. Superclass has its own fields and methods Subclass inherits all of superclass fields and methods and adds some of its own Subclass has its own fields and methods

  4. Inheritance Advantages • One superclass for lots of subclasses • Saves code rewriting for client • Save code rewriting within class • Note: There does not have to be an object of a superclass – there are no “animal” objects, but there may be: (triangle, isosceles triangle, right angle isosceles triangle).

  5. Shapes Example • Circle has: • color, xPosition, yPosition, Diameter • Triangle has: • color, xPosition, yPosition, length, height • Make a parent: Shape

  6. Subtyping Shape s1 = new Shape(); // ok Circle c = new Circle(); // ok Triangle t = new Triangle(); // ok Shape s2 = new Circle(); //ok.all circles are shapes Circle c2 = new Shape(); // NOT ok. not all shapes // are circles --------- c.findCircumference ( ); // ok if method exists s2.findCircumference( ); // NOT ok (Circle)s2.findCircumference(); // ok s2 is a Circle LHS must be same level or higher than RHS object must be same level or lower than method

  7. Polymorphic variables • Object variables in Java are polymorphic.(They can hold objects of more than one type.) • They can hold objects of the declared type, or of subtypes of the declared type. Shape s1; s1 = new Shape(); s1 = new Circle(); s1 = new Triangle(); • s1 is three different types (in the same program), s1 is polymorphic.

  8. Polymorphism: assignment • a = b; // all b are a • b must be able to "fit into"/be lower than/be a subclass of a • b IS-A a (note: backwards of assignment order) • does NOT work for a IS-A b (same order as assignment)

  9. Polymorphism: objects & methods obj.method( ) • method must be in obj class or obj must be cast to the class where method appears • obj can be cast to a LOWER class (subclass), but will get a run-time error if obj is NOT the subclass • If method is an super class, ok without casting. that's the point of inheritance.

  10. Mammal private final int nbrlegs = 4; private final stuff covering = FUR; ----------- Mammal() { // constructor} FeedsYoung() { nurses();} GivesBirth() { liveyoung(); } Practice Dog d = new Mammal(); Mammal m = new Dog( ); StBernard s = new Dog(); m.FeedsYoung( ); d.slobbers(); s.wagstail(); s.FeedsYoung(); Dog // fields for dogs ------- Dog() {// constructor } public void wagstail() { } StBernard // fields for St. Bernards ------ StBernard { /* constructor*/} public void slobbers() { }

  11. Practice 8.11: Assume we have 4 classes: Person, Teacher, Student and PhDStudent. Teacher and Student are both subclasses of Person. PhDStudent is a subclass of Student. Which of the following are legal and why? Person p1 = new Student( ); Person p2 = new PhDStudent( ); PhDStudent phd1 = new Student ( ); Teacher t1 = new Person( ); Student s1 = new PhDStudent( ); s1 = p1; s1 = p2; p1 = s1; t1 = s1; s1 = phd1; phd1 = s1;

  12. Practice 2 8.17 Look at the code below. You have four classes (O, X, T and M) and a variable of each of these. O o; X x; T t; M m; The following assignments are all legal: m = t; m = x; o = t; The following assignment are all illegal: o = m; o = x; x = o; What can you say about the relationships of these classes?

  13. public class Shape { private String color; private int xPosition; private int yPosition; Shapes() // constructor { // do something constructor-like } // methods } Inheritance code for Shape parent classes are no different from any classes we have written.

  14. public class Circle extends Shape { private int diameter; Circle() { super(); // Shapes ctor // more constructor stuff } // other Circle methods } inheritance is implemented with “extends” Inheritance code for Circle Must call parent constructor as first line of subclass constructor

  15. Superclass constructor call • Subclass constructors must always contain a 'super' call. • If none is written, the compiler inserts one (without parameters) • works only, if the superclass has a constructor without parameters • Must be the first statement in the subclass constructor.

  16. arrow with open head means inherits from Shapes Don't try this at home: Shapes inheritance is natural, but doesn't work well with what we know now. Problem: Circle cannot access private fields of Shape (like xPosition), so cannot draw itself. But Shape doesn't know enough about Circles to draw it. So, draw() can’t be in Circle or Shape, so circles can't be drawn. One solution is to make some parts protected (Chapter 9) or make Shapes an abstract class (Chapter 10).

  17. Inheritance: what do we know? • extends // used in subclass • superclass has no indication inheritance is being used • super() // calls constructor of superclass • must be first statement of subclass

  18. Book Example: DoME "Database of Multimedia Entertainment" • stores details about CDs and videos • CD: title, artist, # tracks, playing time, got-it, comment • Video: title, director, playing time, got-it, comment • allows (later) to search for information or print lists This and the next 10 slides are from OBWJ instructor web page.

  19. DoME objects

  20. DoME classes

  21. Using inheritance

  22. Subclasses public class CD extends Item { private String artist; private int numberOfTracks; // constructors and methods omitted. } public class Video extends Item { private String director; // constructors and methods omitted. }

  23. Superclass: Item public class Item { private String title; private int playingTime; private boolean gotIt; private String comment; /** * Initialise the fields of the item. */ public Item(String theTitle, int time) { title = theTitle; playingTime = time; gotIt = false; comment = ""; } // methods omitted }

  24. Inheritance and constructors public class CD extends Item { private String artist; private int numberOfTracks; /** * Constructor for objects of class CD */ public CD(String theTitle, StringtheArtist, int tracks, int time) { super(theTitle, time); artist = theArtist; numberOfTracks = tracks; } // methods omitted }

  25. Database source code public class Database { private ArrayList items; /** * Construct an empty Database. */ public Database() { items = new ArrayList(); } /** * Add an item to the database. */ public void addItem(Item theItem) { items.add(theItem); } ... } Taakes Advantage: Uses Item, not CD or Video otherwise would have one addItem for CDs, one for videos (that's how original is)

  26. Subtyping and parameter passing public class Database { public void addItem(Item theItem) { ... } } Video video = new Video(...); CD cd = new CD(...); database.addItem(video); database.addItem(cd); subclass objects may be passed to superclass parameters

  27. Object diagram

  28. Class diagram without inheritance

  29. Class diagram with inheritance Much cleaner. subtyping takes care of different types.

  30. Polymorphic variables • Object variables in Java are polymorphic.(They can hold objects of more than one type.) • They can hold objects of the declared type, or of subtypes of the declared type. • Big advantage in many applications

  31. Polymorphic collections • All (pre-Java 5)collections are polymorphic. • The elements are of type Object.public void add(Object element)public Object get(int index)

More Related