Docsity

Lecture 8: Inheritance and EPuzzle Class in CS2110 – Summer 2008, Study notes of Computer Science

Toggle sidebar
bg1
1
Inheritance
Lecture 8
CS2110 – Summer 2008
Gregor Johann Mendel (1822–1884)
2
What is Inheritance?
• OO-programming = Encapsulation + Extensibility
• Encapsulation:permits code to be used without knowing
implementation details
classes, objects
visibility declarations such as private, protected
• Extensibility:permits behavior of classes to be changed or
extended without having to rewrite the code of the class
no need to involve the class implementer
promotes code reuse
• Mechanism for extensibility in OO-programming: Inheritance
3
Running Example: 8-Puzzle
class Puzzle {
//representation of a puzzle state
private int state;
//create a new random instance
public void scramble() {...}
//say which tile occupies a given position
public int tile(int row, int col) {...}
//move a tile
public boolean move(char c) {...}
}
857
624
31
4
Representation of State
• One possibility: model puzzle state as an integer between
123456789 and 987654321
9 represents the empty square
• To convert integer s into a grid representation:
Remainder s%10: tile in bottom right position: 8
Quotient s/10: encoding of remaining tiles: 1394267 5
Repeat remainder and quotient to extract remaining tiles
• A similar encoding is used for multidimensional arrays
• We declared state private, so only the Puzzle class knows we
are using this representation -- Encapsulation
139426758
857
624
31
5
New Requirement
• Suppose you are the client. After receiving puzzle code,
you decide you want the code to k eep track of the number
of moves made since the last scra mble operation.
• Implementation is simple:
keep a counter numMoves, initialized to 0
method move should increment the counter
method scramble should reset the counter to 0
new method printNumMoves for printing value of counter
6
Implementation
• Three approaches:
Call supplier and send them a new specification.
They implement it and charge you an extra $5K.
Rewrite the supplier’s code yours elf.
Use inheritance to define a new class that extends
the behavior of the supplier’s class. ☺
pf3
pf4
pf5

Partial preview of the text

Download Lecture 8: Inheritance and EPuzzle Class in CS2110 – Summer 2008 and more Study notes Computer Science in PDF only on Docsity!

1

Inheritance

Lecture 8

CS2110 – Summer 2008

Gregor Johann Mendel (1822–1884)

2

What is Inheritance?

  • OO-programming = Encapsulation + Extensibility
  • Encapsulation: permits code to be used without knowing implementation details ƒ classes, objects ƒ visibility declarations such as private , protected
  • Extensibility: permits behavior of classes to be changed or extended without having to rewrite the code of the class ƒ no need to involve the class implementer ƒ promotes code reuse
  • Mechanism for extensibility in OO-programming: Inheritance

3

Running Example: 8-Puzzle

class Puzzle {

//representation of a puzzle state private int state;

//create a new random instance public void scramble() {...}

//say which tile occupies a given position public int tile(int row, int col) {...}

//move a tile public boolean move(char c) {...} }

4

Representation of State

  • One possibility: model puzzle state as an integer between 123456789 and 987654321 ƒ 9 represents the empty square
  • To convert integer s into a grid representation: ƒ Remainder s%10 : tile in bottom right position: 8 ƒ Quotient s/10 : encoding of remaining tiles: 13942675 ƒ Repeat remainder and quotient to extract remaining tiles
  • A similar encoding is used for multidimensional arrays
  • We declared state private, so only the Puzzle class knows we are using this representation -- Encapsulation

New Requirement

  • Suppose you are the client. After receiving puzzle code,

you decide you want the code to keep track of the number

of moves made since the last scramble operation.

  • Implementation is simple: ƒ keep a counter numMoves , initialized to 0 ƒ method move should increment the counter ƒ method scramble should reset the counter to 0 ƒ new method printNumMoves for printing value of counter

Implementation

• Three approaches:

ƒ Call supplier and send them a new specification.

They implement it and charge you an extra $5K. /

ƒ Rewrite the supplier’s code yourself. /

ƒ Use inheritance to define a new class that extends

the behavior of the supplier’s class. ☺

7

Goal

  • Define a new class EPuzzle that extends Puzzle
  • Tell Java that EPuzzle is just like Puzzle , except: ƒ it has a new instance variable numMoves ƒ it has a new instance method printNumMoves ƒ it has modified versions of scramble and move

8

Picture

state scramble() tile() move()

Puzzle EPuzzle state scramble() tile() move() numMoves printNumMoves()

9

class EPuzzle extends Puzzle { private int numMoves = 0; public void scramble() {...} public boolean move(char d) {...} public void printNumMoves() {...} }

  • Class EPuzzle is a subclass of class Puzzle
  • Class Puzzle is a superclass of class EPuzzle
  • An EPuzzle object ƒ has its own instance variable numMoves and instance method printNumMoves ƒ overrides methods scramble and move of Puzzle ƒ inherits method tile of Puzzle

10

Class Hierarchy

Object

Puzzle Array

EPuzzle

subclass of Puzzle and Object

superclass of EPuzzle and Puzzle

superclass of EPuzzle subclass of Object

Every class (except Object ) has a unique

immediate superclass, called its parent

Overriding

• A method in a subclass overrides a method in

superclass if:

ƒ both methods have the same name,

ƒ both methods have the same signature (number

and type of parameters and return type), and

ƒ both are static methods or both are instance

methods.

Single Inheritance

  • Every class is implicitly a subclass of Object
  • A class can have exactly one parent ƒ class Puzzle {…} - implicitly extends Object ƒ class EPuzzle extends Puzzle {…} - explicitly extends Puzzle , and implicitly extends Object since Puzzle is a subclass of Object
  • Class hierarchy in Java is a tree ƒ subclasses = descendants, superclasses = ancestors
  • In C++, a class can have more than one superclass

(multiple inheritance)

ƒ class hierarchy is a directed acyclic graph (dag)

19

Code for EPuzzle

class EPuzzle extends Puzzle { ...

public void scramble() { state = "978654321"; //OK since state inherited numMoves = 0; }

//similar code for move }

20

Protected Access

  • When should variables and methods be declared

protected instead of private?

  • Think about extensibility: if subclasses will want

access to a member, it should be declared

protected

  • Analogy: ƒ Which components of a car might a user want to upgrade? ƒ What wires/subsystems need to be exposed to make the upgrade easy?

21

Another Solution

  • Suppose a class S overrides a method m in its parent
  • Methods in S can invoke the overridden method in the

parent as

super.m()

  • In particular, can invoke the overridden method in the

overriding method!

  • Caveat: cannot compose super more than once as in

super.super.m()

22

Another Definition of EPuzzle

class EPuzzle extends Puzzle { protected int numMoves = 0; ... public void scramble() { super.scramble(); numMoves = 0; } public boolean move(char d){ boolean p = super.move(d); if (p) numMoves++; //legal move? return p; } }

Do not need protected access to state after all!

Subtypes

  • Inheritance gives a mechanism for creating subtypes ƒ ( Interfaces are another such mechanism)
  • If class B extends class A then B is a subtype of A
  • Examples: ƒ Puzzle p = new EPuzzle(); //up-casting ƒ EPuzzle e = (EPuzzle)p; //down-casting

Unexpected Consequence

An overriding method cannot have more

restricted access than the method it overrides

class A { public int m() {...} }

class B extends A { private int m() {...} //illegal! }

A supR = new B(); //upcasting supR.m(); //would invoke private method in class B at runtime!

25

Shadowing Variables

  • Like overriding, but for fields instead of methods ƒ Superclass: variable v of some type ƒ Subclass: variable v perhaps of some other type ƒ Method in subclass can access shadowed variable using super.v
  • Variable references are resolved using static binding (i.e., at compile-time), not dynamic binding (i.e., not at runtime) ƒ Variable reference r.v uses the static type (declared type) of the variable r , not the runtime type of the object referred to by r
  • Shadowing variables is bad medicine and should be avoided

26

Constructors

  • Each class has its own constructor
  • No overriding of constructors
  • Superclass constructor can be invoked explicitly

within subclass constructor using super() with

parameters as needed

  • Can invoke other constructors of the same class

using this()

  • Call to super() or this() must occur first in the

constructor

27

Abstract Classes

  • An abstract class cannot be instantiated
  • May have methods without bodies that must be

overridden by a (non-abstract) subclass

abstract class Puzzle { protected int state; public void scramble() { state = 978654321; }

//abstract methods (no code) abstract public int tile(int r, int c); abstract public void move(char d); }

28

Abstract Classes

• An abstract class is an incomplete

specification

ƒ Cannot be instantiated directly

ƒ Not all methods in abstract class need to be

abstract ― allows code sharing

ƒ Abstract classes are part of the class hierarchy and

the usual subtyping rules apply

Use of Abstract Classes

  • Variables/methods common to a bunch of related

subclasses can be declared once in Person and

inherited by all subclasses

  • If subclass wants to do something differently, it can

override parent’s methods as needed

Student

abstract class Person

Employee Alum

Conclusion

• Key features of object-oriented programming

ƒ Encapsulation: classes and access control

ƒ Inheritance: extending or changing the behavior of

classes without rewriting them from scratch

ƒ Dynamic storage allocation & garbage collection

ƒ Access control: public/private/protected

ƒ Subtyping