Objectoriented Programming - PowerPoint PPT Presentation

1 / 33
About This Presentation
Title:

Objectoriented Programming

Description:

and perform in some fashion. Inheritance. relationship: Group common properties high in the inheritance hierarchy so that all ... – PowerPoint PPT presentation

Number of Views:37
Avg rating:3.0/5.0
Slides: 34
Provided by: erajbas
Category:

less

Transcript and Presenter's Notes

Title: Objectoriented Programming


1
Object-oriented Programming
  • Overview
  • The inheritance relationship is-a
  • Method overriding
  • Visibility Modifiers
  • Polymorphism and dynamic method binding
  • The keyword super and this
  • Variable shadowing
  • Constructors under inheritance
  • Single implementation inheritance
  • Multiple interface inheritance
  • Assigning, and casting references
  • The instanceof operator

2
Example
  • 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 from these.
  • Even if implementation is unknown, include
    method stubs high in the
  • inheritance hierarchy so that sub classes can
    inherit and override these.

3
Example
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 Why dont
we define this??
4
Example
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
5
Example
Subclasses (Cat extends Animal i.e. A cat is an
animal or All cats are animals)
class Cat extends Animal public Cat()
strNoise Meow // 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
6
Example
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
7
Inheritance 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.

8
Polymorphism 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.
9
Polymorphism
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?
Output? / Reasoning?
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)
10
Polymorphism
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)
11
Polymorphism
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 Child c2 (Child)p c2.childOnlyMethod
()
Output? / Reasoning?
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)
12
Polymorphism
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)
13
Polymorphism
  • Parent p child (or Parent p new Child())

is possible because of inheritance. the Child
is a Parent. Therefore, a parent reference
can reference a child object. This is also known
as Upcasting.
  • p.doStuff()

Because of method overriding. The doStuff
method is redefined in the Child. In order to
get method overriding, the signature have to
match.
  • p.parentOnlyMethod()

Because of inheritance. The subclass Child
inherits the method parentOnlyMethod()
  • p.childOnlyMethod()

Not accessible through a Parent reference.
Methods exclusively in the subclass cannot be
accessed via a super class reference.
14
Polymorphism
  • child (Child) p

Called Down casting. This requires an explicit
cast. Why?
Warning May through a ClassCastException Ex.
Casting a String to a MyString (in project 2)
will cause a ClassCastException. -Try
passing a String object to the equals Method and
then downcasting.
15
A 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)
What is output / reasoning from each line above?
16
A 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 (7) Down
casting (8) Overriding (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)
17
Implications 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
18
Let there be lightConstructor chaining under
inheritance
class Light protected int noOfWatts
//wattage protected boolean indicator //on/off
protected String location //placement
private static int counter0 //no of light
objects public Light() this(0,false)
What does this do?
How is location set? public
Light(int noOfWatts, boolean indicator)
counter setNoOfWatts(noOfWatts) if
(indicator) switchOn() else
switchOff() public void switchOn()
indicator true public void switchOff()
indicator false public boolean isOn()
return indicator public void setNoOfWatts(int
watts) public static void
writeCounter() System.out.println(Number of
lights counter) //
class TubeLight extends Light private int
tubeLength private int color public
TubeLight() setTubeLength(3) What about 3
inher. Vars? setColor(1) public
TubeLight(int length, int color)
this(length, color,30) public
TubeLight(int len, int col, int wat)
super(wat, false) setTubeLength(len)
setColor(col // public static void
main(String args) TubeLight t1 new
TubeLight() TubeLight t2 new
TubeLight(3,1) TubeLight t3 new
TubeLight(3,1,50)
19
Constructors under inheritance
The keyword super refers to the superclass, from
the perspective of the current-class, while the
keyword this refers to the current-class.
Javas rule
If first line of constructor is not an explicit
call to a superclass constructor, Java will
implicitly put super() as the fist line, calling
the superclasss default constructor. A call
to a superclass constructor has to be the first
line of code of a constructor, or not at all.
public TubeLight() setTubeLength(3)
setColor(1) public TubeLight(int length,
int color) this(length, color,30)
public TubeLight(int l, int c, int w)
super(w, false) setTubeLength(length)
setColor(color)
Implicit call to Light()
None of Supers constructors will be called from
here.
Explicit call to Light(int, int) What if We
remove this?
20
Question if a super class had at least 1
non-default constructor and no default
constructor, would a subclass explicitly have to
invoke a super class constructor?
More super and this
21
Variable Shadowing
A subclass cannot override variables of a
superclass - but it can shadow them. That
means, it can have its own variable of the same
type as the superclass without a conflict with
that of the superclass. A subclass can use super
to access the inherited member variable.
When a method is invoked using a reference it
is the class of the current object , not the
reference that determines which method to run.
However, in the case of a variable, it is the
class of the reference, not the class of the
current object denoted by the reference, that
determines which variable will actually be
accessed
Important Difference between methods and
variables under inheritance
22
Example Remember the class Light, Tubelight,
shadowing
public class Light public String billType
Small bill // protected double
getBill(int noOfHours) double smallAmount
10.0 smallAmount smallAmount
noOfHours System.out.println(billTypesm
allAmount) return smallAmount
public void banner() System.out.println(L
et there be light!)
public class TubeLight extends Light public
String billType Large bill // public
double getBill(int noOfHours) double
largeAmount 100.0 largeAmount
largeAmount noOfHours System.out.println(bi
llTypelargeAmount) return largeAmount
public double getBill()
System.out.println(no bill) return 0.0

23
class NeonLight extends TubeLight // public
void demonstrate() this.banner() this.getBil
l(20) this.getBill() System.out.println(this
.billType) TubeLight tl this tl.banner()
tl.getBill(20) tl.getBill() Syst
em.out.println(tl.billType) Light l
this l.banner() l.getBill(20) l.getBill()
System.out.println(l.billType) public
class Client public static void main(String
args) NeonLight neonRef new
NeonLight() neonRef.demonstrate()
Whats the output? Why?
24
class NeonLight extends TubeLight //
public void demonstrate() this.banner() this.g
etBill(20) this.getBill() System.out.println(t
his.billType) super.banner() super.getBill
(20) super.getBill() System.out.println(
super.billType) ((Light) this).banner() ((Lig
ht) this).getBill(20) ((Light)
this).getBill() System.out.println(((Light)
this).billType) public class Client
public static void main(String
args) NeonLight neonRef new
NeonLight() neonRef.demonstrate()
whats going on here? Now can you tell what the
output is and why?
Reasoning Inheritance Method Overriding Extending
the super class Most local variable Inheritance Me
thod overriding Extending the super
class Variable Shadowing Inheritance Method
Overriding Can only access methods that are in
Light Variable Shadowing
Output Let there be light! Large bill 2000.0 No
bill Large bill Let there be light! Large bill
2000.0 No bill Large bill Let there be
light! Large bill 2000.0 ltcompiler Errorgt Small
bill
25
Applied Inheritance
  • Decide on the classes involved from the problem
    description
  • Group classes into conceptually equivalent groups
  • Per group of classes, the generalizing concept
    will be a Parent to those classes
  • Distribute responsibilities amongst all classes
    based on what is appropriate
  • and customary for that class.

Example
A program to teach geometry needs to model some
basic shapes. All shapes have surface area,
could have volume and location. The shapes that
need to be modeled are Circle, Rectangle,
Sphere, Cylinder, and a Square. What classes
will you need? Draw an UML diagram showing class
relationships if any.
26
Example
Classes Circle, Rectangle, Sphere, Cylinder,
Square, Coordinate
Group classes
All Shapes
2D Shapes
Circle
Sphere
Coordinate
Rectangle
Cylinder
Square
3D Shapes
Square is a Rectangle
Inheritance hierarchy
27
Example
Distribute Responsibilities
Shape getSurfaceArea() clone() equals() toStr
ing() Object getLocation()
Shape3D getVolume()
Shape2D ?
Is Shape2D needed?
28
Example Abstract classes.
public abstract class Shape public double
getSurfaceArea() public Object
getLocation() public Object clone()
public String toString() public boolean
equals()
Observe the syntax of Shape. The methods are not
empty methods
Abstract Class
A class with at least one unimplemented method.
Shape above is an example of an Abstract class.
Interface
A class with only unimplemented methods.
public interface Shape public double
getSurfaceArea() public Object
getLocation() public Object clone()
public String toString() public boolean
equals()
29
Interfaces vs Abstract classes, how to decide?
Not all programming languages have Interfaces!
1 unimplemented method
2 unimplemented method
All methods unimplemented
All methods implemented

Abstract class
Interface
Regular Class
So why have abstract classes and interfaces?
  • To enforce design conformity.
  • Clients can expect a uniform set of methods for
    related classes.
  • Interfaces are used to tag a class with a
    property. While interfaces
  • are classes, they represent action ideas,
    verbs or properties
  • about class.

30
Interfaces...
Sample Interfaces
Cloneable, Drawable, Colorable, Runable,
Comparable,
Q How do you inherit from an interface? A By
implementing the interface.
public interface Shape implements Cloneable
public abstract class Shape2D implements Shape

Q How do you inherit from an Abstract class? A
The usual way, by extending
public class Circle extends Shape2D
31
Its all still inheritance!
public interface Shape implements Clonable
public abstract class Shape2D implements
Shape public class Circle extends
Shape2D
Client Code Circle c new Circle() Shape s
c Cloneable cln s Shape2D s2d (Shape2D)s
  • Circle has to implement all
  • unimplemented methods of
  • 2DShape
  • Shape
  • Clonable

32
Its all still inheritance!
Client Code Circle c new Circle() Shape s
c Cloneable cln s Shape2D s2d
(Shape2D) s
through c you can access ALL methods of Circle
AND its parents!
Through s you can access ONLY methods of Shape
and Cloneable implemented in Circle
Through cln you can access ONLY methods of
Cloneable implemented in Circle
Through s2d you can access ONLY methods of Shape,
Cloneable, and Shape2D implemented in Circle.
33
Multiple Inheritance
Some programming languages allow for multiple
inheritance.
In Java
Can have multiple interface inheritance Single
Inheritance.
Types of possible inheritance
  • An interface can inherit from multiple interfaces
    by implementing
  • A class (abstract or otherwise) can inherit from
    multiple interfaces by
  • implementing
  • A class (abstract or otherwise) can inherit from
    a single other (abstract or
  • normal) class.
Write a Comment
User Comments (0)
About PowerShow.com