lec14 - 1.00 Lecture 14 Inheritance, part 2 Reading for...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: 1.00 Lecture 14 Inheritance, part 2 Reading for next time: Big Java: sections 9.1-9.4 Exercise: Plants • Create a base class Plant: Plant – Private data genus, species, isAnnual genus species isAnnual – Write the constructor • Create a derived class Tree: Tree – Class declaration extends ________ extends ________ – Private data crownSize, trunkSize crownSize trunkSize – Write the constructor 1 Exercise class Plant class Plant { ____________________________ ____________________________ ____________________________ ____________________________ ____________________________ ____________________________ ____________________________ ____________________________ Plant(_____________________________) public Plant(_____________________________) { ____________________________ ____________________________ ____________________________ ____________________________ ____________________________ ____________________________ ____________________________ ____________________________ } } Tree extends ______ class Tree extends ______ { ____________________________ ____________________________ ____________________________ ____________________________ ____________________________ ____________________________ ____________________________ ____________________________ Tree(_____________________________) public Tree(_____________________________) { ____________________________ ____________________________ ____________________________ ____________________________ ____________________________ ____________________________ ____________________________ ____________________________ } Plant Exercise, p.2 • Create a derived class Flower Flower – Class declaration extends _______ extends _______ – Private data blossomColor blossomColor – Write constructor • Create a derived class Rose Rose – Class declaration extends _____ extends _____ – Private data thornDensity thornDensity – Write constructor • Create a derived class Pine Pine – Class declaration extends ______ extends ______ – Private data needleType, coneType needleType coneType – Write constructor 2 Exercise class Flower extends ______ class Flower extends ______ { ____________________________ ____________________________ ____________________________ ____________________________ Flower(_____________________________) public Flower(_____________________________) { ____________________________ ____________________________ ____________________________ ____________________________ } } Rose extends ______ class Rose extends ______ { ____________________________ ____________________________ ____________________________ ____________________________ Rose(_____________________________) public Rose(_____________________________) { ____________________________ ____________________________ ____________________________ ____________________________ } } Pine extends _____ class Pine extends _____ { ____________________________ ____________________________ ____________________________ ____________________________ Rose(_____________________________) public Rose(_____________________________) { ____________________________ ____________________________ ____________________________ ____________________________ }} Exercise, p.3 • Write a class PlantTest PlantTest – It has just a main() method, which: main() • Creates a Plant, Tree, Flower, Rose, Pine Plant, Tree, Flower, Rose, Pine • Genus and species examples: – – – – – Pinus contorta Rosa villosa Quercus alba (white oak) Narcissus jonquilla (daffodil) Prenanthes boottii (Boott’s rattlesnake root) • Pick other data as you wish – Step through the debugger to see how the constructors are called 3 Constructors • Sub class invokes constructors of super class – Constructors invoked in order of inheritance public class Base{ public class Base{ Base() public Base() { System.out.println("Base"); System.out.println("Base"); } } class Derived extends Base public class Derived extends Base { Derived() public Derived() { System.out.println("Derived"); System.out.println("Derived"); } } public class DerivedAgain extends Derived { class Derived DerivedAgain() public DerivedAgain() { System.out.println("Derived Again"); } } class Constructor1 public class Constructor1 { static void main(String args) public static void main(String args) { new DerivedAgain();}} DerivedAgain Object1= new DerivedAgain();}} Output: Base Derived Derived DerivedAgain DerivedAgain Default constructor invoked unless another constructor explicitly called. Some constructor must be invoked. Abstract classes • Classes can be very general at the top of a class hierarchy. – For example, MIT could have a class Person, from Person which Employees, Students, Visitors, etc. inherit Employees Students Visitors – Person is too abstract a class for MIT to ever use in a computer system but it can hold name, address, name address status status, etc. that is in common to all the subclasses – We can make Person an abstract class: Person objects Person Person cannot be created, but subclass objects, such as Student Student, can be • Classes can be concrete or abstract 4 Abstract classes, p.2 • Another example (leading to graphics in the next lectures) – Shape class in a graphics system – Shapes are too general to draw; we only know how to draw specific shapes like circles or rectangles – Shape abstract class can define a common set of methods that all shapes must implement, so the graphics system can count on certain things being available in every concrete class – Shape abstract class can implement some methods that every subclass must use, for consistency: e.g., objectID objectType objectID, objectType Shape class public abstract Shape public abstract class Shape { public abstract void draw(); abstract void draw(); Drawing function must be implemented in each // Drawing function must be implemented in each derived class but no default is possible: // derived class but no default is possible: abstract error(String message) public void error(String message) { … } Error function must be implemented in each derived // Error function must be implemented in each derived class and default is available: non­ method // class and a default is available: non­abstract method final objectID() public final int objectID() { … } Object ID function: each derived class must have one // Object ID function: each derived class must have one and must use this implementation: method // and must use this implementation: final method …}; class Square extends Shape {…}; public class Square extends Shape {…}; class Circle extends Shape {…}; public class Circle extends Shape {…}; 5 Abstract method • Shape is an abstract class (keyword) abstract – No objects of type Shape can be created Shape • Shape has an abstract method draw() draw() – draw() must be redeclared by any concrete (nondraw() abstract) class that inherits it – There is no definition of draw() in Shape draw() Shape – This says that all Shapes must be drawable, but the Shape Shape Shape class has no idea of how to draw specific shapes Non-abstract method • Shape has a non-abstract method error() error() – Each derived class may handle errors as it wishes: • It may define its own error method using this signature (method arguments/return value) • It may use the super class implementation as a default – If it overrides the superclass method, it must have exactly the same signature as the superclass method • If you write a method with same name but different arguments or return type, it’s considered a new method in the subclass • This is an easy mistake to make. Be careful. – This can be dangerous: if new derived classes are added and programmers fail to redefine non-abstract methods, the default will be invoked but may do the wrong thing • E.g. kangaroos 6 Final method • Shape has a final method objectID objectID – Final method is invariant across derived classes – Behavior is not supposed to change, no matter how specialized the derived class becomes • Super classes should have a mix of methods – Don’t make all abstract super class methods abstract. Take a stand! An aside: final classes • To prevent someone from inheriting from your class, declare it final: public class Grad extends Student public final class Grad extends Student { … • This would not allow SpecGrad to be built • Class can have abstract, final or no keyword abstract final Exercise • Write an abstract Person class – Protected variables name, age, address, ID – Private static variable nextID • Initialize it to 1 – Write constructor w/name, age, address args – Write abstract printData() method – Write non-abstract error() method • Prints “error” if age<0, or name or address is null – Write final method getID() 7 Exercise, p.2 • Write a concrete Student class – Extends Person – Has additional private variable: year (undergrad year 1-4) – Write constructor – Write printData() method • Must have same signature as base class’ – Write error() method • Also write error message if year<1 or year>4 – Try to write a getID() method • What happens? Exercise, p.3 • Write a class AbstractTest – Has only a main() method, which: • Tries to create a Person object – What happens? • Creates and prints data for a valid Student • Creates an invalid Student with negative age, null address and year=5 • Calls error method – Where should error() really be called? • Go back to Person and make name private rather than protected – What happens? – What would you need to add to Person if name were private? 8 Fun with animals class Bird class Bird { void fly(); public void fly(); }; … }; Penguin extends Bird class Penguin extends Bird { }; … }; Birds can fly // Birds can fly Penguins are birds // Penguins are birds // // Problems: Problems: If is final, Penguins must fly If superclass fly() is final, Penguins must fly // // If is abstract or non­ non If superclass fly() is abstract or non­abstract, Penguin’s fly() can print an error, etc. It’s clumsy Penguin’s fly() can print an error, etc. It’s clumsy // // // With inheritance, every subclass has every method and With inheritance, every subclass has every method and data field in the superclass. You can never drop data field in the superclass. You can never drop anything. This is design challenge in real systems. anything. This is a design challenge in real systems. Possible solutions Bird Penguin Bird Crow FlyingBird Crow NonFlyingBird Penguin Decision depends on use of system: If you’re studying beaks, difference between flying and not flying may not matter 9 More issues Quadrilateral MoveCorner() Rectangle MoveCorner() Must override the MoveCorner() method in subclasses to move multiple corners to preserve the correct shape 10 ...
View Full Document

This note was uploaded on 11/29/2011 for the course CIVIL 1.00 taught by Professor Georgekocur during the Spring '05 term at MIT.

Ask a homework question - tutors are online