Title: Isa
1Is-a
2 Inheritance, Polymorphism and Interface
3OO principles
- Everything is an object
- A program is a set of objects that interact by
sending messages (i.e. function calls) - Each object has its own state
- Every object has a type (i.e. class)
- All object of the same type can receive the same
set of messages - Every object has state, behavior, identity
4Other major OO concepts
- Inheritance
- Polymorphism
- Late (dynamic) binding
-
5Inheritance
- Inheritance provides us with a way of
- taking advantage of similarities between objects
from different classes - building new classes that are extensions of
existing classes
6Inheritance in Real World
- How is a student like a person?
- Well, every student is a person!
- Students have all of the properties of persons,
plus some others. - For example, every person has a name and an age
- and so does every student.
- However, not every person is a student.
- Every student has a student id and a grade point
average, that other persons don't have.
7Subclass and Superclass
- In Java, we model a person by a Person class.
- In Java, we model a student by a Student class.
- Since a student is like a person with extra
properties, we say the class Student is a
subclass of the class Person. - We also say that Person is a superclass of
Student.
8Inheritance Tree
- In general, Person can have other
- subclasses as well, say Teacher.
- We put all the classes in an inheritance tree
with class Object as the root. - We draw the tree with the root at the top.
9A Tree
Object
Person
Teacher
Student
10Java inheritance
- extends keyword
- a subclass inherits all of the instance variables
(and methods, except constructors) and all of the
static variables (and methods) of its superclass - Singly-rooted class hierarchy
- All classes implictly subclass java.lang.Object
- Provides equals(), toString(), hashCode()and more
basic services - No multiple inheritance
11protected
- Visibility modifier, like public or private
- Allows public-like access to subclasses
- And to classes in same package
- For all other classes it is like private
- Rationale its a way to pass over to
subclasses some feature, without making it
visible to client classes. - e.g. field enginePower in MotorVehicle
- Makes sense to make it visible to Truck, Car etc.
12Methods Inheritance
- In Java, a subclass inherits all of the methods
of its superclass, so they do not have to be
re-implemented - However, you can also override any method if you
want to - Overriding is not the same as overloading!
- In addition, you can add some code to an
inherited method, using the super object
reference.
13Inheritance and Constructors
- Costructors are NOT inherited
- A subclass instance includes a superclass
instance - Objects are constructed/initialized top-down
- Superclass constructor must be called first
- Which constructor?
- Default superclass constructor is implicitly
called - If it does not exist, compiler will complain
- If programmer wants another superclass
constructor to be called, she must specifiy that
super()keyword
14Inheritance and Constructors Example
- public class Person
- // Each instance represents a Person.
- // Constructors
- public Person()
- // Set the name unknown and height
- name "unknown"
- Height 160
- //
-
- public Person(String nameString)
- // Set the given name and height
- this( ) // do the 0 argument constructor first
- this.name nameString
-
15Inheritance and Constructors Example
- public class Student extends Person
- // Each instance represents a Student.
- public Student()
- // Set the name "unknown", height160, id 0
- this.id 0 // implicit call to super() first
-
- public Student(String nameString)
- // Set the given name, height160, id 0
- super(nameString) // explicit call
- this.id 0
-
- public Student(String nameString, int anInt)
- // Set the given name height and id,
- this(nameString) // or super(nameString)
- this.id anInt
-
16super()
Has no default constructor
class SuperClass public SuperClass(String
param) System.out.println("SuperClass
constructor " param) class SubClass
extends SuperClass public SubClass()
System.out.println("SubClass constructor")
public SubClass(String param)
super(param) System.out.println("SubClass
constructor " param) public static
void main(String args) SubClass sub new
SubClass(args0)
Call to super() must be 1st statement in
constructor
What is going to happen?
17Substitutability
- A variable of some class can then be bound to an
instance of that class or any subclass. - Any message that can be sent to an instance of a
class can also be sent to an instance of its
subclasses. - If the type of a method parameter or the return
type of a method is a class, you can use any
subclass as well. - The principle of being able to use an instance of
a subclass, wherever you can use an instance of a
class is called substitutability.
18Substitutability Example
- Person class has setName (String) method
- Student class
- Person p new Person (Lin)
- Student s new Student (Mike, 9909)
- p new student (John, 1230)
- //p can be bounded to any kind of person
- p.setName(new name)
- s.setName(new name)
- //message setName can be sent to any kind of
Person
19Substitutability Example
- Assume that class Store has a method called
register that takes a Person as a parameter - public void register(Person aPerson)
- //Register the given Person as a customer.
-
- Store sto
- //.. Some code to create sto
- sto.register(p)
- sto.register(s)
20Overridding
- Instance methods and static methods can be
overridden in a subclass - Overriding methods shadow the method of the
superclass - If there are multiple implementations of a method
within the inheritance hierarchy of an object,
the one in the most derived class (lowest in
the tree) overrides the others, even if we refer
to the object via a less derived type
21Overload and Override
- Overloaded methods are selected by the compiler
at compile time - Overridden methods are selected dynamically by
the Virtual Machine at runtime - There is a small performance penalty to pay for
dynamic binding - VM has to search for the
overridden methods in subclasses.
22Example Shapes
- Inheritance and Polymorphism
- Classic example easy to understand
- All geometric shapes are types in themselves
23Our Task
- Suppose were writing a new, super-powerful
drawing program - This program is so powerful, it can draw both
circles and squares - And in the future who knows! we might be able
to draw triangles, and ellipses
24Inelegant Approach
- We define two classes, Circle and Square
- Each class has fields size, location, and color
- Each implementation also holds an extra integer
field called type, that is always set to 1 if
its a Circle and 2 if its a Square
25Inelegant Approach (cont.)
- As the user draws, we save their drawing as a
list of things, where a thing can be either a
Circle or a Square - To draw things, we have to looks at the type
field, and if its a 1 it calls method
drawCircle() on the thing, and if its a 2 it
calls drawSquare().
26Circle
Square
- int type 1
- long size
- long color
- long coordX
- long coordY
- int type 2
- long size
- long color
- long coordX
- long coordY
Circle() - drawCircle()
Square() - drawSquare()
27Elegant Approach
- We define a class Shape that has fields size,
location, and color. - We define two more classes, Circle and Square
- Each extends Shape
- In each of these two subclasses we define a
specific draw() method. - Each defines its own algorithm, so Circles
draw() draws a circle, and Squares draw() draws
a square - They override the original draw()
28class Drawing Shape myShapes ...
public void refresh () for (int i0int lt
myShapes.lengthi) myShapesi.draw()
extends
29Elegant Approach (cont.)
- Both draw() methods use the size, location, and
color fields, although these are not directly
defined in the subclass. The fields are
inherited from the superclass. - We have a list of shapes, and we ask each shape
to draw itself. - NOTE the correct method is called each time
this is polymorphism
30Late binding
- Polymorphism seems a bit magic
- Not only draw() of Shape is overridden
- But each time the right draw() is invoked!
- The code to be executed for each call is not
pre-determined by the compiler - Early vs. late binding
- Run-time language support resolves what code is
to be executed each time - by looking at the actual type of the object
involved in the call
31Casting
- A cast tells the compiler to perceive an object
reference as a different type - Unlike some other languages, Java performs type
checking at compile-time and runtime - Casting is only legal between objects in the same
inheritance hierarchy - Cant cast a Point to a Date, for example! a
ClassCastException is thrown if you attempt to
cast an object to an incompatible type at runtime
32Casting Example
- Person p new Person( )
- Student s new Student( )
- p s
- // legal, Substitutability rule
- // s p
- // compile-time error, incompatible type
- p new Student()
- s (Student) p
- // legal
33Casting
- Casting does not change the reference or the
object being pointed to. It only changes the
compiler/VMs treatment of the reference - A common usage of Casting When we take an Object
reference out of a Container (e.g. Vector) and
cast it to another type (e.g. String) we are
performing a narrowing cast
34Casting Summary
- Implicitly cast an object to a less derived type
(i.e. a class higher up the tree) - If you have an Object that you know is of a more
derived type you can downcast it ( narrow) - If youre not sure of the type of an object, you
must use instanceof before performing the cast,
to avoid a ClassCastException at runtime
35instanceof
- The instanceof operator can be used to determine
the type of an object at runtime - Use it to compare an object against a particular
type - Returns a boolean
- true if the object is of the specified class
- false otherwise
36Example
- boolean result
- String aString Fred
- result (aString instanceof String) // true
- result (aString instanceof Object) // true
- result (aString instanceof Point) // false
- aString null
- result (aString instanceof String) // false
37Object Class
- clone()
- equals()
- finalize()
- toString()
- hashCode()
- notifiy()
38Abstract classes
- Inheritance hierarchy
- Sometimes base class is an entity you want to
instantiate - Sometimes it is just an abstract type
- Defines a useful set of concepts and functions
but not an entity that needs instances - Example Shape
- You instantiate Circles, Squares etc.
- abstract keyword
39abstract
- A class is abstract (cant be instantiated) if
- Has 1 or more abstract methods
- or is itself declared abstract
- Invoking new on an abstract class makes compiler
complain - Abstract methods have no code
- Declare an API without defining its
implementation - Implementation is delegated to non-abstract
subclasses satisfying the same API
abstract class Shape
public abstract void doSomething()
40An example
- abstract class Shape
- private long color
- Shape(long color)
- this.color color
-
- public long getColor()
- return color
-
- ...
- public abstract double computeArea()
41(No Transcript)
42Interfaces
- An abstract class declares an API
- Not pure API
- Some of the implementation is carried out there
- Some is delegated to subclasses
- Contract plus some content
- Makes sense if some of the code logically belongs
into the abstract class - Java provides means for defining pure APIs as
well, called interfaces - Only contract definition
- abstract classes to the extreme
43interface / implements
- Create an interface like you would a class
- In a file ltinterface_namegt.java
- List methods belonging to the interface
- A class can then be declared to implement that
interface
public interface myInf void myMethod1()
int myMethod2(int i)
Class access rules apply to interfaces as well
must provide public implementations of all myInf
methods
Class myClass implements myInf public void
myMethod1() public int myMethod2(int i)
44More on interfaces
- Can subclass interfaces
- extends keyword
- Can have fields in interfaces
- They are public, static and final
- To be immediately assigned
- Good device for defining sets of constants
- Refer to them as ltinterface_namegt.ltconstant_namegt
interface subInf extends SuperInf1, superInf2
...
45Interfaces and inheritance
- More than just abstract classes to the extreme
- While a class can extend only one class
- it can implement any number of interfaces
- A way around the absence of multiple inheritance
in Java - Allows to assign and combine freely features and
functionality to classes - Actually to their APIs
46interface CanFly
abstract class Bird
fly()
extends
implements
interface CanSwim
swim()
47Example Comparable Interface
48 Common interfaces of the Java API
49Common interfaces of the Java API
50final and Inheritance
- Final keyword can be applied to prevent some of
the inheritance effects - final field i.e. constant
- final argument cannot change data within called
method - final method i.e. cannot override method in
subclasses - final class i.e. cannot subclass it
- All of its methods are implicitly final as well
- Rationale design and/or efficiency
51Java inheritance review
- extends inherit and specialize
- protected share a field / method with subclasses
- abstract declare contract, delegate (part of)
implementation - interface
- pure API, no implementation, not even partial
- multiple APIs (? multiple inheritance)
- advanced type modeling
- final limits inheritance effects
52Wrap up
- OO and Java
- OO concepts
- Inheritance
- Polymorphism
- Late binding
- Casting
- Abstract classes
- Interfaces
53Software Engineering Observation 8.9
- One form of software reuse is composition, in
which a class has as members references to
objects of other classes.
54Has-a
55Outline
56Outline
Validates month value
Validates day value
57Outline
Check if the day is February 29 on a leap year
58Outline
Employee contains references to two Date objects
Implicit calls to hireDate and birthDates
toString methods
59Outline
Create an Employee object
Display the Employee object