24
Inheritance Chapter 9

Inheritance Chapter 9. Inheritance Superclass Subclass subclass of Animal superclass of dog and cat

  • View
    258

  • Download
    9

Embed Size (px)

Citation preview

Inheritance

Chapter 9

InheritanceSuperclass

Subclass

subclass of Animalsuperclass of dog and cat

Mammalprivate final int nbrlegs = 4;private final stuff covering = FUR;-----------Mammal() { // constructor}FeedsYoung() { nurses();}GivesBirth() { liveyoung(); }

Dog// fields for dogs-------Dog() {// constructor }public void wagstail(){ }

Cat// fields for cats--------Cat() { // constructor}public void ignore(){ }

Superclass has its own fields and methods

Subclass has its own fields and methods

Subclass inherits all of superclass

fields and methods and

adds some of its own

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, xPosition, yPosition, Diameter

Triangle has:color, xPosition, yPosition, length, height

Make a parent: Shape

Shapeint xPosition;int yPosition;String Color;-------// constructor and methods

Circleint diameter;-----Circle methods

Squareint length;----Square methods

Triangleint height, length;---Triangle methods

Shapeint xPosition;int yPosition;String Color;-------// constructor and methodsmoveVertical(int n)all other methods

Circleint diameter;-----Circle methodsdraw( )changeSize(int newSize)

Triangleint height, length;---Triangle methodsdraw( )changeSize(int newH, int newL)

Assignment

Circle c = new Circle ( ); Shape s = new Shape( ); s = c; // ok, a circle IS a shape c = s; // NOT ok. A shape might be

something other than a Circle

Assignment a = b; // all b are a b must the same class as a, or a subclass of a b IS-A a (note: backwards of assignment order)

dog is a mammalCircle is a Shape

does NOT work for a IS-A b (same order as assignment)mammal is not necessarily a dog

Objects & methodsobj.method( )

method must be in obj class or a parent class Circle c = new Circle(); c.draw( ); // ok. draw is a Circle method c.changeColor("green"); // ok. changeColor is a Shape method

Shape s; s.draw( ) ; // NOT ok. draw is a method of its children s.changeColor("green"); // ok. changeColor is a Shape method

If method is in the super class, ok. that's the point of inheritance.

Subtyping

Object variables in Java can hold objects of the declared type, or of subtypes of the declared type.

Big advantage in many applications

SubtypingShape s1 = new Shape( ); // okCircle c = new Circle( ); // okTriangle 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 existss2.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

Casting

4 / 3 = 1

Creates a new value, 4.0 (double) from 4

Casting

3 is automatically coerced into a double. Casting does it explicitly, and is programmer controlled

Turn one type into another (when it’s ok) double sphere = 4 / 3 * Math.PI * r * r * r;

fix: double sphere = (double) 4 / 3 * Math.PI * r * r * r;

4.0 / 3 = double/ int = double / double = 1.333…

Casting and Inheritance PracticeA. Ok B. Not OK1. int y=3; double g=3;2. int x = (double) y;3. double z = (int) g;4. MyShape s = new Circle( );5. Circle c = new Circle( );6. s.moveVertical(10);7. c.moveVertical(10);8. c.findCircumference( );9. s.findCircumference( );10. ((Circle) s).findCircumference( );

critical}Also critical}

Methods and Inheritance

ok to call method in the class or in a superclass NOT ok to call method of a subclass To do that, object must be cast to the class where

method appears ((Circle) s).draw( ); // no syntax error

// ok if s is a Circle

Will get a run-time error if object is NOT the subclass Shape s = new Square( ) ; // ok ((Circle) s).draw( ); // ok in syntax. run time error

Mammalprivate final int nbrlegs = 4;private final stuff covering = FUR;-----------Mammal() { // constructor}FeedsYoung() { nurses();}GivesBirth() { liveyoung(); }

Dog// fields for dogs-------Dog() {// constructor }public void wagstail() { }

StBernard// fields for St. Bernards------StBernard { /* constructor*/}public void slobbers() { }

1. Dog d = new Mammal();

2. Mammal m = new Dog( );

3. StBernard s = new Dog();

4. m.FeedsYoung( );

5. d.slobbers();

6. s.wagstail();

7. s.FeedsYoung();

PracticeA. OK B. NOT OK

Practice: A. OK B. Not OKAssume 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?

1. Person p1 = new Student( );2. Person p2 = new PhDStudent( );3. PhDStudent phd1 = new Student ( );4. Teacher t1 = new Person( );5. Student s1 = new PhDStudent( );

6. s1 = p1;7. s1 = p2;8. p1 = s1;9. t1 = s1;10. s1 = phd1;11. phd1 = s1;

Practice 2: do on the board8.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?

public class Superclass

{

}

public class Subclass extends Superclass

{

}

Inheritance Syntax

Inheritance code for Personpublic class Person{private String name;

public Person() // constructor { // do constructor-like stuff }

public Person(String n){ name = n; }

public void getName( ){ return name; }// other methods}

parent classesare no different

from any classeswe have written.

Code for Studentpublic class Student extends Person{ private String school;

public Student( ) { super( ); school = "Christopher Newport University"; }

public Student(String name, String school) { super(name); this.school = school; } public void getSchool( ) { return school; }}

Must call parent constructor as first line of subclass constructor

inheritance is implemented

with “extends”

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.

Client using Person and StudentA. OK; B. NOT ok

public class MyClient{ Person p = new Person( ); Student s = new Student( ); Person r = new Student( ); public MyClient( ) { p.getName( ); // 1 s.getSchool( ); // 2 s.getName( ); // 3 r.getSchool( ); // 4 }

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