inheritance recitation - 02/22/2008 cs 180 department of computer science, purdue university

32
Inheritance Recitation - 02/22/2008 CS 180 Department of Computer Science, Purdue University

Post on 20-Dec-2015

217 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Inheritance Recitation - 02/22/2008 CS 180 Department of Computer Science, Purdue University

Inheritance Recitation - 02/22/2008

CS 180

Department of Computer Science,

Purdue University

Page 2: Inheritance Recitation - 02/22/2008 CS 180 Department of Computer Science, Purdue University

Announcements

Project 3 grades are out. Collect at the end of the recitation.

Project 5 has been posted. 2-week project.

Milestone due 27th Feb. Final submission due 5th March.

You are seriously recommended to start it early.

A reminder regarding the course policy for CS180 - A first instance of academic dishonesty will result in a

zero for that assignment plus a letter grade deduction at the end of the semester.

Page 3: Inheritance Recitation - 02/22/2008 CS 180 Department of Computer Science, Purdue University

Introduction to Inheritance

Inheritance allows us to define a general class and then define more specialized classes simply by adding new details to the more general class definition.

A more specialized class inherits the properties of the more general class, so that only new features need to be programmed.

An inherit class (or a sub-class) can inherit properties from more than one super-class.

Page 4: Inheritance Recitation - 02/22/2008 CS 180 Department of Computer Science, Purdue University

Introduction to Inheritance, cont.

Example General class Vehicle might have instance

variables for weight and maximum occupancy.

More specialized class Automobile might add instance variables for wheels, engine size, and license plate number.

General class Vehicle might also be used to define more specialized classes Boat and Airplane.

Page 5: Inheritance Recitation - 02/22/2008 CS 180 Department of Computer Science, Purdue University

Programming Example: A Base Class

class Person{

private String name;public Person(){

name = “no name”;}public Person(String _name){

name = _name;}

//setName(String) and getName() methods//sameName(String) method//writeOutput() method

}

Page 6: Inheritance Recitation - 02/22/2008 CS 180 Department of Computer Science, Purdue University

Derived Classes Consider a college record-keeping system with

records about students, faculty and staff. All these specific groups are sub-classes of the class

Person.

Page 7: Inheritance Recitation - 02/22/2008 CS 180 Department of Computer Science, Purdue University

Derived Classes, cont.

Even though your program may not need any Person or Student objects, these classes can be useful for consolidating and representing features common to all subclasses.

For example, all students, faculty, and staff have names, and these names may need to be initialized, changed, retrieved, or printed.

Page 8: Inheritance Recitation - 02/22/2008 CS 180 Department of Computer Science, Purdue University

Derived Classes, cont.

• class Student is a sub-class of class Person and class Person is called the base class.

public class Student extends Person{

private int studentNumber;

public Student(String _name, int _num){

super(_name);

studentNumber = _num;

}

//more methods not in Person class

//writeOutput() overwrites the method in Person class

}

Page 9: Inheritance Recitation - 02/22/2008 CS 180 Department of Computer Science, Purdue University

Derived Classes, cont.

When you define a derived class, you declare only the added instance variables and you define only the added and overridden methods.

The variables and methods of the parent class which are not declared private are inherited automatically.

Protected variables are available only to classes derived from the class. different than public.

Page 10: Inheritance Recitation - 02/22/2008 CS 180 Department of Computer Science, Purdue University

Derived Classes, cont.

class InheritanceDemo

Page 11: Inheritance Recitation - 02/22/2008 CS 180 Department of Computer Science, Purdue University

Overriding Method Definitions

A particular sub-class might require a specific method already in the base-class to work differently. This calls for overriding that method.

Notice that class Student has a method writeOutput(), and class Person also has a method writeOutput()redefined.

When a derived class defines a method with the same name and the same number and types of parameters as a method in the base class, the method in the derived class overrides/replaces the method in the base class.

Page 12: Inheritance Recitation - 02/22/2008 CS 180 Department of Computer Science, Purdue University

Overriding vs. Overloading

When you override a method, the new method definition in the derived class has the same name and the same number of types of parameters as the method definition in the base class. Overriding is like replacing the derived method

from the super-class by your own.

When the name is the same, but the number or types of the parameters (the signature) differs, the method is overloaded.

Page 13: Inheritance Recitation - 02/22/2008 CS 180 Department of Computer Science, Purdue University

Constructors in Derived Classes

A base class has its own constructors. Their purpose typically is to initialize the

instance variables declared in the base class.

A derived class has its own constructors Their purpose typically is to call a

constructor in the base class, and then to initialize the instance variables declared in the derived class.

Page 14: Inheritance Recitation - 02/22/2008 CS 180 Department of Computer Science, Purdue University

Using super

The call to the constructor in the super class (using the keyword super) must be the first action taken in the constructor of a sub-class.

When no call to the constructor in the super class is included, Java automatically includes a call to the default constructor in the base class.

super(initialName);notPerson(initialName); //Illegal!!

Page 15: Inheritance Recitation - 02/22/2008 CS 180 Department of Computer Science, Purdue University

Using super, cont.

equivalent definitions:public Student(){

super();studentNumber= 0;

}

andpublic Student(){

//java automatically includes a call to the //default constructor of the super-class

studentNumber= 0;}

Page 16: Inheritance Recitation - 02/22/2008 CS 180 Department of Computer Science, Purdue University

The this Method Recall that within the definition of one

constructor, a call to another constructor in the same class can be made using the this keyword.

Example – Student() {

this (“Default Name”, 0);}Student(String name, int _num) {

…..}

Page 17: Inheritance Recitation - 02/22/2008 CS 180 Department of Computer Science, Purdue University

The this Method, cont.

Any use of this must be the first action in the constructor definition. Thus, a constructor definition cannot contain a

call using super and a call using this. To use both super and this, include a call using

this in one constructor and a call using super in the constructor called using this. Example –

Student() {this (“Default Name”, 0);

}Student(String name, int _num) {

super();…..

}

Page 18: Inheritance Recitation - 02/22/2008 CS 180 Department of Computer Science, Purdue University

Calling an Overridden Method

super can be used to call a method in the base class that has been overridden in the derived class.

Example super.writeOutput(); The above line in the Student class would call the

overridden writeOutput() method in the Person class. This need not be the first line of code.

You cannot use super to invoke a method in some ancestor class other than the immediate base (parent) class.

Page 19: Inheritance Recitation - 02/22/2008 CS 180 Department of Computer Science, Purdue University

An Object Can Have More than One Type

If class Undergraduate is derived from class Student and class Student is derived from class Person, then every object of class Undergraduate is also an object of class Student and an object of class Person.

A reference to an object of a sub-class can be substituted for a reference of an ancestor class.

However, a reference to an object of an ancestor cannot be substituted for a reference to an object of a derived class.

Page 20: Inheritance Recitation - 02/22/2008 CS 180 Department of Computer Science, Purdue University

The Class Object

In Java, every class descends from (and inherits features from) the Object class.

Therefore, every object of every class is of type Object.

Unless a class is declared explicitly to be a descendant of some other class, it is an immediate descendant of the class Object.

An object of any class can substituted when a parameter of type Object is expected.

Page 21: Inheritance Recitation - 02/22/2008 CS 180 Department of Computer Science, Purdue University

The Class Object, cont.

Every class inherits some methods from the class Object: equals() toString()

but usually these methods are overridden by the derived class or by an intermediate ancestor class.

Method toString Inherited method toString takes no arguments. Typically, method toString is coded to produce and

return a string which contains everything of interest about the object.

Page 22: Inheritance Recitation - 02/22/2008 CS 180 Department of Computer Science, Purdue University

Abstract Classes

An abstract class is not intended to be used to create objects.

Abstract method – By declaring one or more methods to be abstract and by omitting the method body, only objects of derived classes which override the method(s) can be instantiated.

examplepublic abstract void drawHere();

A class that has at least one abstract method must be declared abstract.

Page 23: Inheritance Recitation - 02/22/2008 CS 180 Department of Computer Science, Purdue University

Abstract Classes, cont.

Public abstract class Figure{

private int offset;

public abstract void drawHere();

public void drawAt(int num){

int count;

for(count = 0; count < num; count++){

System.out.println();

}

drawHere();

}

}

Page 24: Inheritance Recitation - 02/22/2008 CS 180 Department of Computer Science, Purdue University

Interfaces

An interface specifies the headings for methods that must be defined for any class that implements the interface.

Example -

Page 25: Inheritance Recitation - 02/22/2008 CS 180 Department of Computer Science, Purdue University

Interfaces, cont.

A class that implements an interfaces must implement all the methods specified by the interface.

To implement an interface, a class must include the phrase

implements Interface_Name

at the start of the class definition example

class CS180 implements Writable {…} implement all the method headings listed in

the definition of the interface.

Page 26: Inheritance Recitation - 02/22/2008 CS 180 Department of Computer Science, Purdue University

Dynamic Binding

Different objects can invoke different method definitions using the same method name.

For example, if Square and Triangle are sub-classes of the class Figure,

and s and t are both objects of type Figure,where s references a Square and t references a Triangle, b and t invoke different definitions of method computeArea()

Page 27: Inheritance Recitation - 02/22/2008 CS 180 Department of Computer Science, Purdue University

Dynamic Binding, cont.

Handling the invocation of a method that may be overridden later is called dynamic binding or late binding.

The type of object being referenced at the time of the method call, not the type of reference that was declared, determines which method is invoked. Example – Consider class Student with sub-classes Graduate and

UnderGraduate, each with writeOutput() overridden. Student s1 = new Graduate(); Student s2 = new UnderGraduate(); s1.writeOutput() and s2. writeOutput() make calls to two

different methods.

Page 28: Inheritance Recitation - 02/22/2008 CS 180 Department of Computer Science, Purdue University

Another Dynamic Binding Example

Recall the Person class with sub-classes Student, Graduate, Staff etc.Person[] x = new Person[100];

x[0] = new Student();

x[1] = new Graduate();

x[2] = new Staff();

..

How does the compiler decide which method x[i].writeOutput() is calling?

Page 29: Inheritance Recitation - 02/22/2008 CS 180 Department of Computer Science, Purdue University

Determining Class Type

The following are the ways to determine class type of an object. (x instanceof A) – returns true if x is an instance of class

A or a subclass of A

x.getClass().equals(A.class) – true if x is an instance of class A

A.class.isAssignableFrom(x.getClass()) is true if x is an instance of class A or a subclass of A

Page 30: Inheritance Recitation - 02/22/2008 CS 180 Department of Computer Science, Purdue University

Determining Class Type

public class Animal {protected int age;

public void makeSound() { SOP(“Make sound!”); }}

public class Ferret extends Animal {public Ferret() { super(); }

public void eatSweets() { SOP(“Yummy!”); }public void makeSound() { SOP(“Squeal!”); }

}

public class Platypus extends Animal {public Platypus() { super(); }

public void swim() { SOP(“Swim!”); }public void makeSound() { SOP(“Quack!”); }

}

Animal a = new Ferret();

if (a instanceof Ferret)((Ferret)a).eatSweets();

a = new Platypus();

if (a.getClass() == Platypus.class)((Platypus)a).swim();

if (Platypus.class.isAssignableFrom(a))((Platypus)a).swim();

________________________________

Animal a = new Ferret();((Platypus)a).swim(); // compiles, but runtime error!

Page 31: Inheritance Recitation - 02/22/2008 CS 180 Department of Computer Science, Purdue University

Subtle Difference

Dynamic binding refers to the process carried out by the computer.

Polymorphism can be thought of as something objects do.

Polymorphism, encapsulation, and inheritance and considered to be the main features of object-oriented programming.

Page 32: Inheritance Recitation - 02/22/2008 CS 180 Department of Computer Science, Purdue University

Quiz

abstract public class Animal {…}

abstract public class Bird extends Animal {…}

abstract public class Mammal extends Animal {…}

abstract public class Fish extends Animal {…}

public class Owl extends Bird {…}

public class Bat extends Mammal {…}

public class Whale extends Mammal {…}

public class Shark extends Fish {…}

Which instantiations are valid?

Animal a = new Animal();Animal b = new Fish();Animal c = new Shark();Mammal d = new Bat();Fish e = new Mammal();Bird b = new Owl();

GGiven the following declarations, whichof the shown instantiations are valid?