Inheritance Chapter 8 Inheritance Superclass subclass of Animal
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 Mammal private final int nbrlegs = 4; private final stuff covering = FUR; -----Mammal() { // constructor} Feeds. Young() { nurses(); } Gives. Birth() { liveyoung(); } Dog // fields for dogs ------Dog() {// constructor } public void wagstail() {} Cat // fields for cats -------Cat() { // constructor} public void ignore() {} Subclass has its own fields and methods
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).
Shapes Example • Circle has: – color, x. Position, y. Position, Diameter • Triangle has: – color, x. Position, y. Position, length, height • Make a parent: Shape
Shape int x. Position; int y. Position; String Color; ------// constructor and methods Circle int diameter; ----Circle methods Square int length; ---Square methods Triangle int height, length; --Triangle methods
Subtyping Shape s 1 = new Shape(); // ok Circle c = new Circle(); // ok Triangle t = new Triangle(); // ok Shape s 2 = new Circle(); //ok. all circles are shapes Circle c 2 = new Shape(); // NOT ok. not all shapes // are circles LHS must be same level ----- or higher than RHS c. find. Circumference ( ); // ok if method exists must be same level s 2. find. Circumference( ); // NOT ok object or lower than method (Circle)s 2. find. Circumference(); // ok s 2 is a Circle
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 s 1; s 1 = new Shape(); s 1 = new Circle(); s 1 = new Triangle(); – s 1 is three different types (in the same program), s 1 is polymorphic.
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)
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.
Mammal private final int nbrlegs = 4; private final stuff covering = FUR; -----Mammal() { // constructor} Feeds. Young() { nurses(); } Gives. Birth() { liveyoung(); } Dog // fields for dogs ------Dog() {// constructor } public void wagstail() { } Practice Dog d = new Mammal(); Mammal m = new Dog( ); St. Bernard s = new Dog(); m. Feeds. Young( ); St. Bernard // fields for St. Bernards -----St. Bernard { /* constructor*/} public void slobbers() { } d. slobbers(); s. wagstail(); s. Feeds. Young();
Practice 8. 11: Assume we have 4 classes: Person, Teacher, Student and Ph. DStudent. Teacher and Student are both subclasses of Person. Ph. DStudent is a subclass of Student. Which of the following are legal and why? Person p 1 = new Student( ); Person p 2 = new Ph. DStudent( ); Ph. DStudent phd 1 = new Student ( ); Teacher t 1 = new Person( ); Student s 1 = new Ph. DStudent( ); s 1 = p 1; s 1 = p 2; p 1 = s 1; t 1 = s 1; s 1 = phd 1; phd 1 = s 1;
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?
Inheritance code for Shape public class Shape { private String color; private int x. Position; private int y. Position; Shapes() // constructor { // do something constructor-like } // methods } parent classes are no different from any classes we have written.
inheritance is implemented with “extends” Inheritance code for Circle public class Circle extends Shape { private int diameter; Circle() { super(); // Shapes ctor // more constructor stuff } // other Circle methods } Must call parent constructor as first line of subclass constructor
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.
arrow with Don't try this at home: open Shapes inheritance is natural, but doesn't work well head with what we know now. means inherits Problem: Circle cannot access private fields of from Shape (like x. Position), 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. Shapes One solution is to make some parts protected (Chapter 9) or make Shapes an abstract class (Chapter 10).
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
Book Example: Do. ME "Database of Multimedia Entertainment" • stores details about CDs and videos – CD: title, artist, # tracks, playing time, gotit, 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.
Do. ME objects
Do. ME classes
Using inheritance
Subclasses public class CD extends Item { private String artist; private int number. Of. Tracks; // constructors and methods omitted. } public class Video extends Item { private String director; // constructors and methods omitted. }
public class Item { private String title; private int playing. Time; private boolean got. It; private String comment; Superclass: Item /** * Initialise the fields of the item. */ public Item(String the. Title, int time) { title = the. Title; playing. Time = time; got. It = false; comment = ""; } // methods omitted }
Inheritance and public class CD extends Item { constructors private String artist; private int number. Of. Tracks; /** * Constructor for objects of class CD */ public CD(String the. Title, String the. Artist, int tracks, int time) { super(the. Title, time); artist = the. Artist; number. Of. Tracks = tracks; } // methods omitted }
public class Database { private Array. List items; Database source code /** * Construct an empty Database. */ public Database() T { a items = new Array. List(); a } k e /** s * Add an item to the database. */ public void add. Item(Item the. Item) { items. add(the. Item); }. . . } Advantage: Uses Item, not CD or Video otherwise would have one add. Item for CDs, one for videos (that's how original is)
Subtyping and parameter passing public class Database { public void add. Item(Item the. Item) {. . . } } Video video = new Video(. . . ); CD cd = new CD(. . . ); database. add. Item(video); database. add. Item(cd); subclass objects may be passed to superclass parameters
Object diagram
Class diagram without inheritance
Class diagram with inheritance Much cleaner. subtyping takes care of different types.
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
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)
- Slides: 32