Title: Objectoriented Programming
1Object-oriented Programming
- Overview
- The inheritance relationship is-a
- Method overriding
- Visibility Modifiers
- Polymorphism and dynamic method binding
- The keyword super
- Variable shadowing
- Constructors under inheritance
- Single implementation inheritance
- Multiple interface inheritance and supertypes
- Assigning, and casting references
- The instanceof operator
2What is inheritance?
3Inheritance
Natural, hierarchical way of organizing things.
(superclass)
Animal
(subclasses of Animal)
Dog
Cat
Biped
(subclass of )
Retriever
Guard
Lion
Tiger
Human
(subclass of )
Labrador
German Shepherd
Think in terms of is a relationships A Lion
is a Cat, and so is a Tiger A Labrador is a
Retriever is a Dog is a Animal A Human is a(n)
Biped is a Animal.
4Another hierarchy
Light
Artificial Light
Natural Light
Light Bulb
Tube Light
SpotLight Bulb
NeonLight
- Inheritance defines the relationship is-a (also
called superclass-subclass - relationship) between a superclass and a
subclass. - Classes higher up are more generalized as they
abstract the class behavior. - Classes lower down are more specialized as they
customize the inherited - (abstract) behavior using additional properties
and behavior.
5Inheritance - Overview
Class A
- Class B inherits from Class A, or
- Class B extends Class A
- Class A is the more general form while Class B is
a specialization.
Class B
Class B contains
- All of the properties of A
- Its own methods, not found in A (EXTENDING class
A) - Methods of A that were redefined in B.
(OVERRIDING)
Class A
Class B must belong to the same family as A. You
must be able to say
B is a A
6The Java Object class
All classes in Java Inherit from the Object
class Any object is-a(n) Object The Object class
is always the root of any inheritance hierarchy
7A simple example of Inheritance
Reason possible
Foo f new Foo() System.out.println(f.getClass()
) System.out.println(f.toString())
inheritance overriding
Java console
java.lang.Foo this is foo
public class Foo public String toString()
return this is foo
UML notation for inheritance between classes.
The arrow originates at the class that is
inheriting (the child).
8Method Overriding
If a class, referred to as Child, inherits from
another class, referred to as Parent, and if the
Parent has a non-static,non-private, non-final
method and the Child also has an identical
method, then the Childs method will replace
(Override) that of the Parent in a Child
object. This characteristic of replacing is
called Method Overriding.
public class Test public main(String
args) Child c new Child()
c.foo()
public class Parent public void foo()
System.out.println(I am a parent)
public class Child extends Parent public
void foo() System.out.println(I am a
child)
Reason Method Overriding
Output I am a child
Warning Dont get Overriding and Overloading
mixed up!
9Method Overriding
- A subclass may override non-static, non-private,
and non-final methods inherited - from a superclass. (So that also means that any
static, private, or final method - cannot be overridden by a subclass.)
- When a method is invoked on an object of the
subclass, it is the new method - definition in the subclass that is executed.
- The new method definition in the subclass must
have the same method - signature (i.e. method name and parameters), and
the same return. - The new definition cannot narrow the
accessibility of the method, but it - can widen it.
- The new method definition can only specify all or
a subset of the exception - classes specified by the throws clause of the
overridden method. - A subclass can use the keyword super to invoke
an overridden method in the - superclass.
10Overriding verses Overloading - what's the
difference?
- Method overriding requires the same method
signature, the same return type - and the original method was inherited from its
superclass. - Overloading requires different method signatures,
but the method name should - be the same.
- (To overload, the parameters must be different in
type and/or number. The - return type is not a part of the signature,
changing it is not enough to - overload methods.)
- A method can be overloaded in the class it is
defined in, or in a subclass. - To invoke an overridden method in the superclass
from a subclass, requires the - use of super.
11Visibility Modifiers
public A method/variable that is public is
callable/accessible from within and out side of
the current object
private A method/variable that is private is
callable/accessible from only within the current
object only.
protected A method or variable that is protected
is accessible from within the objects of the
current class and from within objects of
subclasses provided the subclass does not
override or shadow. Protected methods/variables
cannot be called/accessed from outside the
current or subclass.
protected variables/methods are similar to
private variables/methods from the clients
perspective. Anything designated private cannot
be inherited. Items designated private are
accessible only within objects of that class only.
12Visibility Modifiers ...
public class Parent protected int a private
int b public int c protected void
pMethod1() System.out.println(Parentmethod1
) private void pMethod2()
System.out.println(Parentmethod2)
public void pMethod3() method2()
method1()
public class Child extends Parent public void
cMethod1() pMethod1() pMethod2()
pMethod3()
public class Client public static void
main() Child c new Child()
c.cMethod1() c.pMethod1()
c.pMethod2() c.pMethod3()
A childs method that overrides a parent method
cannot narrow the methods visibility
public method protected method - no client
access private method - no client access public
method - public access
13Example
- Want to model relationships between the following
classes - Animal
- Cat
- Dog
- Biped
- Lets assume that all of these objects have
- have a name
- make a sound
- and perform in some fashion
Inheritance relationship
Design goals
- Group common properties high in the inheritance
hierarchy so that all - sub classes inherit these.
- Even if implementation is unknown, include
method stubs high in the - inheritance hierarchy so that sub classes can
inherit and override these.
14Example
class Animal protected String strName
protected String strNoise
protected int iNumTimesPerformed 0
protected static int population 0
//assume constructors public void
setName(String strName) this.strName
strName public String getName() return
strName public void setNoise(String
noise) public void identifySelf(
) System.out.println(My name is
strName) // of identifySelf public
void perform ( ) doYourThing( )
iNumTimesPerformed // of perform
public void doYourThing( ) // no-op
method // of doYourThing // of Animal
So, animals have a name and noise and they can
identify themselves, perform and do their thing.
Animal harpo new Animal() harpo.setName(Harpo
) harpo.doYourThing() // says nothing
15Example
Subclasses (Dog extends Animal i.e. A dog is an
animal or All dogs are animals)
class Dog extends Animal public Dog()
strNoise Woof // of constructor
public void doYourThing ( )
identifySelf() System.out.println(I am a
dog) System.out.println(strNoise)
// of doYourThing // of Dog
Recall The Animal class had a no-op method for
doYourThing()
Dog pickles new Dog() pickles.setName(Pickles
) pickles.doYourThing() // output // My name
is Pickles // I am a dog // Woof
16Example
Subclasses (Cat extends Animal i.e. A cat is an
animal or All cats are animals)
class Cat extends Animal public Cat()
strNoise Miaow // of constructor
public void doYourThing ( )
identifySelf() System.out.println(I am a
cat) System.out.println(strNoise)
// of doYourThing // of Cat
Cat abby new Cat() abby.setName(Abby) abby.d
oYourThing() // output // My name is Abby //
I am a cat // Miaow
17Example
Subclasses (Biped extends Animal i.e. A Biped is
an animal or All Bipeds are animals)
class Biped extends Animal public Biped()
strNoise I walk on two legs therefore
I am // of constructor public void
doYourThing ( ) identifySelf()
System.out.println(I walk upright)
System.out.println(strNoise) // of
doYourThing // of Human
Biped descartes new Biped() Biped.setName(Rene
) descartes.doYourThing() // output // My
name is Rene // I walk upright // I walk on
two legs therefore I am
18Inheritance and Scope
- Variables (e.g. strNoise)
- First examines current method, looks for local
variable or parameter - Then examines current class (e.g. Dog)
- Then examines superclass (e.g. Animal)
- Continues up the class hierarchy until no more
superclasses to examine. - Methods (e.g. doYourThing() or identifySelf())
- First examines current class
- Then examines superclass
- Continues up inheritance hierarchy until no
more superclasses to examine.
19Polymorphism and Dynamic method Binding
An object of a subclass can be used wherever an
object of the superclass can be used.
Example An object of TubeLight can be used
whenever an object of the superclass, Light, can
be used, since TubeLight is-a Light
What does this mean?
Light l TubeLight tl new TubeLight() l tl
Why is this reasonable?
Polymorphism and Dynamic Method Binding The
ability of a superclass reference to denote
objects of its own class and those of its
subclasses at runtime is called polymorphism.
The method invoked is dependent on the actual
type of the object denoted by the reference at
runtime.
20Polymorphism
Observe
public class Parent protected int a
public Parent() a 0 public void
doStuff() System.out.println(Parent do
stuff) public void parentOnlyMethod()
System.out.println(Parent only method)
- Both classes have a doStuff method
- Both classes have methods that are
- unique to them
Part 1 What happens now?
Reasoning Constructor method overriding Inherited
Extending parent
Client Code Child child new Child() child.doSt
uff() child.parentOnlyMethod() child.childOnlyMe
thod()
public class Child extends Parent protected
int b public Child () a 0
public void doStuff() System.out.println(C
hild do stuff) public void
childOnlyMethod() System.out.println(Child
only method)
21Polymorphism
public class Parent protected int a
public Parent() a 0 public void
doStuff() System.out.println(Parent do
stuff) public void parentOnlyMethod()
System.out.println(Parent only method)
Part 2 What happens now?
Child child new Child() child.doStuff() child.
parentOnlyMethod() child.childOnlyMethod()
Client Code Parent p child p.doStuff() p.par
entOnlyMethod() p.childOnlyMethod() child
(Child) p
Reasoning bc, Child is-a Parent-
Polymorphism, Upcasting Method overriding Inherita
nce ERROR! Down Casting - Dangerous!
public class Child extends Parent protected
int b public Child () a 0
public void doStuff() System.out.println(C
hild do stuff) public void
childOnlyMethod() System.out.println(Child
only method)
22Polymorphism
- Parent p child (or Parent p new Child())
is possible because of inheritance. the Child
is a Parent. Therefor, a parent reference can
reference a child object. This is also known as
Upcasting.
Because of method overriding. The doStuff
method is redefined in the Child. In order to
get method overriding, the signature have to
match.
Because of inheritance. The subclass Child
inherits the method parentOnlyMethod()
Not accessible through a Parent reference.
Methods exclusively in the subclass cannot be
accessed via a super class reference.
23Polymorphism
Called Down casting. This requires an explicit
cast. Why?
Warning May through a ClassCastException
24A second example - whats the output? Reason
through the statements
class client public static void main(String
args) String stringRef new String(Java)
//(1) System.out.println((2)
stringRef.getClass()) //(2) System.out.println
((3) stringRef.length()) //(3) Object
objRef stringRef //(4) System.out.println(
(5) objRef.equals(Java)) //(5) System.out.p
rintln((6) objRef.getClass()) //(6) string
Ref (String) objRef //(7) System.out.println
((8) stringRef.equals(C) //(8) System.ou
t.println((9) objRef.length()) //(9)
Reasoning (2) Inheritance (3) Extending/Local
method (4) Up casting/Polymorphism (5)
Overriding (6) Inheritance (8) Overriding (7)
Down casting (9) Error!
Output from the program (2) class
java.lang.String (3) 4 (4) (5) true (6) class
java.lang.String (7) (8) false (9)
25Implications of Inheritance
- An object of a subclass can be used wherever an
object of - the superclass can be used.
- The inheritance relationship is Transitive if
class B extends - class A, and class C extends B, then C inherits
from A via B - (An object of SpotLight is-a Light)
- The is-a relationship does not hold between
peer classes. - (A Dog is-NOT-a cat)
- Litmus test for using inheritance if B is
a(n) A, then let - B inherit from A.
Do not use inheritance unless all inherited
behavior makes sense