0% found this document useful (0 votes)
2 views5 pages

Inher

The document discusses inheritance in object-oriented programming (OOP), emphasizing its role in encapsulation and extensibility. It explains how inheritance allows for code reuse and modification without rewriting existing code, using examples like the EPuzzle class extending the Puzzle class. Additionally, it covers access specifiers, the importance of protected variables, and the concept of abstract classes in OOP.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views5 pages

Inher

The document discusses inheritance in object-oriented programming (OOP), emphasizing its role in encapsulation and extensibility. It explains how inheritance allows for code reuse and modification without rewriting existing code, using examples like the EPuzzle class extending the Puzzle class. Additionally, it covers access specifiers, the importance of protected variables, and the concept of abstract classes in OOP.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

What is Inheritance?

• OO-programming = Encapsulation + Extensibility

Inheritance • Encapsulation: permits code to be used without knowing


implementation details
 classes, objects
 visibility declarations such as private, protected

Lecture 8 • Extensibility: permits behavior of classes to be changed or


extended without having to rewrite the code of the class
CS211 – Summer 2007
 no need to involve the class implementer
 promotes code reuse

• Mechanism for extensibility in OO-programming: Inheritance


Gregor Johann Mendel (1822–1884)

1 2

Running Example: 8-Puzzle Representation of State


1 3
1 3 4 2 6 139426758
class Puzzle {
4 2 6 7 5 8
//representation of a puzzle state 7 5 8
• One possibility: model puzzle state as an integer between
private int state;
123456789 and 987654321
//create a new random instance  9 represents the empty square
public void scramble() {...} • To convert integer s into a grid representation:
 Remainder s%10: tile in bottom right position: 8
//say which tile occupies a given position  Quotient s/10: encoding of remaining tiles: 13942675
public int tile(int row, int col) {...}  Repeat remainder and quotient to extract remaining tiles
• A similar encoding is used for multidimensional arrays
//move a tile
• We declared state private, so only the Puzzle class knows we
public boolean move(char c) {...}
are using this representation -- Encapsulation
}
3 4

New Requirement Implementation

• Suppose you are the client. After receiving puzzle code, • Three approaches:
you decide you want the code to keep track of the number
of moves made since the last scramble operation.  Call supplier and send them a new specification.
They implement it and charge you an extra $5K. 
• Implementation is simple:
 keep a counter numMoves, initialized to 0  Rewrite the supplier’s code yourself. 
 method move should increment the counter
 method scramble should reset the counter to 0
 new method printNumMoves for printing value of counter  Use inheritance to define a new class that extends
the behavior of the supplier’s class. 

5 6
Goal Picture

• Define a new class EPuzzle that extends Puzzle


Puzzle EPuzzle
state state
• Tell Java that EPuzzle is just like Puzzle, except: scramble() scramble()
 it has a new instance variable numMoves tile() tile()
 it has a new instance method printNumMoves move() move()
 it has modified versions of scramble and move numMoves
printNumMoves()

7 8

class EPuzzle extends Puzzle { Class Hierarchy


private int numMoves = 0;
public void scramble() {...} superclass of EPuzzle
public boolean move(char d) {...} and Puzzle
Object
public void printNumMoves() {...}
}
superclass of EPuzzle
subclass of Object Puzzle ……. Array
• Class EPuzzle is a subclass of class Puzzle
• Class Puzzle is a superclass of class EPuzzle
• An EPuzzle object subclass of Puzzle
 has its own instance variable numMoves and instance and Object EPuzzle
method printNumMoves
 overrides methods scramble and move of Puzzle
 inherits method tile of Puzzle Every class (except Object) has a unique
immediate superclass, called its parent
9 10

Overriding Single Inheritance


• Every class is implicitly a subclass of Object
• A method in a subclass overrides a method in • A class can have exactly one parent
superclass if:  class Puzzle {…}
• implicitly extends Object
 both methods have the same name,  class EPuzzle extends Puzzle {…}
 both methods have the same signature (number • explicitly extends Puzzle, and implicitly extends Object since
Puzzle is a subclass of Object
and type of parameters and return type), and
• Class hierarchy in Java is a tree
 both are static methods or both are instance  subclasses = descendants, superclasses = ancestors
methods.
• In C++, a class can have more than one superclass
(multiple inheritance)
 class hierarchy is a directed acyclic graph (dag)

11 12
scramble and move
Writing the EPuzzle Class
How should we write scramble and move?
One option: write them from scratch.
class EPuzzle extends Puzzle {
Class EPuzzle extends Puzzle {
private int numMoves = 0;
...
public void printNumMoves() {
public void scramble() {
System.out.println("Number of moves = "
+ numMoves); state = "978654321";
numMoves = 0;
}
}
public void scramble() {...}
public boolean move(char d) {...} public boolean move(char d) {...}
}
}

• Problem: state was declared private in the Puzzle


class
• it is not accessible to EPuzzle!
13 14

Difficulty with Private Variables Interesting Point


EPuzzle
state
• Variable state is declared private, so it is only
scramble()
accessible to methods in class Puzzle
tile()
• In an instance of class EPuzzle, the tile method move()
can access this variable because the tile method is numMoves
inherited from the superclass printNumMoves()
• Method scramble defined in class Epuzzle does not
have access to state •EPuzzle objects have an instance variable state because
EPuzzle extends Puzzle
• Similarly, any private methods in a superclass are not
• However, they cannot access it directly, because it is private!
accessible to methods in subclass •state is accessible to public methods inherited from Puzzle
(such as tile()) but not to methods written in the EPuzzle
class (such as scramble())
15 16

Protected Access
Proper Code for Puzzle Class
• Access specifier: protected
• A protected instance variable in class S can be says state is
accessed by instance methods defined in S or in any accessible from
subclass of S subclasses
class Puzzle {
• A protected method in class S can be invoked from an
protected int state;
instance method defined in S or any subclass of S
public void scramble(){...}
• Access checks are done by compiler at compile time: ...
 For an invocation r.m(): }
• Determine type of reference r
• Does the corresponding class/interface have a method named
m with appropriate arguments?
• Are the access specifiers of that method appropriate?

17 18
Code for EPuzzle Protected Access

class EPuzzle extends Puzzle { • When should variables and methods be declared
...
protected instead of private?
public void scramble() { • Think about extensibility: if subclasses will want
state = "978654321"; //OK since state inherited access to a member, it should be declared
numMoves = 0; protected
}
• Analogy:
//similar code for move  Which components of a car might a user want to upgrade?
}  What wires/subsystems need to be exposed to make the
upgrade easy?

19 20

Another Solution Another Definition of EPuzzle


class EPuzzle extends Puzzle {
• Suppose a class S overrides a method m in its parent protected int numMoves = 0;
...
• Methods in S can invoke the overridden method in the public void scramble() {
parent as super.scramble();
super.m() numMoves = 0;
}
public boolean move(char d){
• In particular, can invoke the overridden method in the boolean p = super.move(d);
overriding method! if (p) numMoves++; //legal move?
return p;
}
• Caveat: cannot compose super more than once as in }
super.super.m()
Do not need protected access to state after all!

21 22

Subtypes Unexpected Consequence


An overriding method cannot have more
• Inheritance gives a mechanism for creating subtypes restricted access than the method it overrides
 (Interfaces are another such mechanism)
class A {
public int m() {...}
• If class B extends class A then B is a subtype of A }

class B extends A {
• Examples: private int m() {...} //illegal!
 Puzzle p = new EPuzzle(); //up-casting }
 EPuzzle e = (EPuzzle)p; //down-casting
A supR = new B(); //upcasting
supR.m(); //would invoke private method in
class B at runtime!

23 24
Shadowing Variables Constructors
• Like overriding, but for fields instead of methods
 Superclass: variable v of some type
• Each class has its own constructor
 Subclass: variable v perhaps of some other type
 Method in subclass can access shadowed variable using super.v
• No overriding of constructors
• Superclass constructor can be invoked explicitly
• Variable references are resolved using static binding (i.e., at
within subclass constructor using super() with
compile-time), not dynamic binding (i.e., not at runtime) parameters as needed
 Variable reference r.v uses the static type (declared type) of the • Can invoke other constructors of the same class
variable r, not the runtime type of the object referred to by r using this()
• Call to super() or this() must occur first in the
• Shadowing variables is bad medicine and should be avoided constructor

25 26

Abstract Classes Abstract Classes


• An abstract class cannot be instantiated
• May have methods without bodies that must be • An abstract class is an incomplete
overridden by a (non-abstract) subclass specification
 Cannot be instantiated directly
abstract class Puzzle {
protected int state;  Not all methods in abstract class need to be
public void scramble() { abstract ― allows code sharing
state = 978654321;  Abstract classes are part of the class hierarchy and
} the usual subtyping rules apply
//abstract methods (no code)
abstract public int tile(int r, int c);
abstract public void move(char d);
}
27 28

Use of Abstract Classes Conclusion


abstract class Person • Key features of object-oriented programming
 Encapsulation: classes and access control
Student Employee Alum  Inheritance: extending or changing the behavior of
classes without rewriting them from scratch
• Variables/methods common to a bunch of related  Dynamic storage allocation & garbage collection
subclasses can be declared once in Dad and inherited  Access control: public/private/protected
by all subclasses  Subtyping

• If subclass wants to do something differently, it can


override parent’s methods as needed

29 30

You might also like