InheritanceAndPolymorphismprein Java.ppt

gayatridwahane 7 views 28 slides Jul 18, 2024
Slide 1
Slide 1 of 28
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28

About This Presentation

Inheritance in Java


Slide Content

CSSE221: Software Dev. Honors Day 6
Announcements
Questions?
Hint on BallWorlds’ changing the x and y coords in
2
nd
half of lecture today.

This week: BallWorlds assignment
Monday:
Intro to UML as a communication tool
Writing methods you don't call
Using this
Tuesday:
Inheritance
Polymorphism
Thursday:
Introducing next week’s assignment
Arrays and ArrayLists
(Using the debugger)

Reminder
For the inheritance, polymorphism, and array
groups, you owe me 3 things:
1.Summary
2.Quiz
3.Answer key

Inheritance slides
Some material from those produced by Fall
2006-2007 CSSE221 students:
Michael Auchter
Michael Boland
Andrew Hettlinger

Inheritance
Objects of different kinds (classes) have their
own unique behavior.
Objects of different kinds often share similar
behavior too.
For example:
Student, Professor, Software Engineer, Chemical
Engineer, Physicist, Guitarist, Drummer
Each has distinct actions to perform, but they also
have many features and behavior in common

Why not just copy-and-paste?
Say I have an Employeeclass and want to
create an HourlyEmployeeclass that adds
info about wages. Why not copy-and-paste,
then modify?
1.Fixing bugs: what if one were wrong?
2.Maintenance: what if Employeechanges?
3.Code-reuse: would code that takes an Employee
as a parameter also take an HourlyEmployee?

The Basics of Inheritance
Inheritance allows you to reusemethods that
you’ve already written to create more specialized
versions of a class.
Java keyword: extends.
public class HourlyEmployee extendsEmployee.
We say that an HourlyEmployee IS-A Employee
Employee is said to be the parent class (or
superclass), and HourlyEmployee is called a child
class (or subclass).
HourlyEmployee receives copies of all of the non-
private methods and variables present in Employee.

Your turn
Quiz question: What is the relationship between
a parrot and a bird?

Some Key Ideas in Inheritance
Code reuse
Overriding methods
Protected visibility
The “super” keyword

Code re-use
The subclass inheritsall the publicand
protectedmethods and fields of the superclass.
Constructors are not inherited
Constructors can be invoked by the subclass
Subclass can add new methods and fields.

Overriding Methods
DudThatMoves will “extend” Dud
If it defines an act()method with the same
signature that overrides Dud’s method
What do you think happens if our child class
doesn’t override a method in the parent class?
It’s exactly the
same as in the
parent class!

Visibility Modifiers
•Public–Accessible by any other class in any package.
•Private–Accessible only within the class.
•Protected–Accessible only by classes within the same
package and any subclasses in other packages.
•(For this reason, some choose not to use protected, but use
private with accessors)
•Default (No Modifier) –Accessible by classes in the
same package but not by classes in other packages.
•Use sparingly!

Protected Visibility
Suppose in Dud you defined:
protected int xPos;
Then:
Instances of children inherit this field
(one for each instance)
Children can access/modify the fields
this.xPosin Dud (parent) and this.xPosin
DudThatMoves (child) refer to same value

The “super” Keyword
It’s like the word “this,” only “super”:
In a child class, “super” refers to its parent.
Two uses:
1.To call a parent’s method, use super.methodName(…)
2.To call a parent’s constructor, use super(some parameter)
from the child class’constructor
Reminder, still use this (super not needed) to
access parent’s fields: this.xPos

The “super” Keyword
Methods can call super.methodName(…)
To do the work of the parent class method, plus…
Additional work for the child class
public class Workaholic extends Worker {
public void doWork() {
super.doWork();
drinkCoffee();
super.doWork();
}
}

The “super” Keyword
Methods can call super.methodName(…)
To do the work of the parent class method, plus…
Additional work for the child class
public class RoseStudent extends Worker {
public void doWork() {
while (!isCollapsed) {
super.doWork();
drinkCoffee();
}
super.doWork();
}
}

Rules of using super in constructors
A super(…)call must be the first line of the
code of an object’s constructor if it is to be
used.
Instance variables cannot be passed along with
the super(…)call. Only variables that are
passed to the constructor that calls supermay
be passed to super.

The thisKeyword
1.this.someFieldand this.someMethod(): nice style
2.thisalone is used to represent the whole object: env.addBall(this)
3.thisis used to call another constructor inside of a method with
multiple constructors.
public class foo {
private String message;
public foo(){
this(“This foo is saaaaaad.”);
}
public foo(String s){
message = s;
}
}
thishas the same restrictions on it as super–that is, it must be the
first thing called in a constructor and it cannot be passed instance
variables.
Therefore, super(…)and this(…)cannot be used in the same
constructor.

Final notes
Every object in Java extends java.lang.Object
Don’t have to say it explicitly
This is why every class has a basic toString() method.
What does it mean for a field to be declared final?
Final fields can’t be assigned a new value
Final methods cannot be overridden
Final classes cannot be extended
There is only single inheritance in Java.
Subclass can be derived only from one superclass.

Inheritance Basics
(a checklist to which to refer)
Classes extending other classes:
Only have to describe how they are different from parents
Don’t have to repeat methods which are “good enough” in the
parent
Can replace or “extend” any method which isn’t “good enough”
Can access parent’s methods and constrcutors via super.
Can share fields with a parent in a “protected” way (say,
this.xPos)
Only need to declare imports they use (like java.awt.Color)
Don’t have to redeclare interfaces of the parent (like
Drawable)

Inheritance Demo
Be sure you finish the quiz
Then take a break

Polymorphism
Polymorphism is the concept of allowing a
reference to a subclass to be used in a place where a
reference to its parent’s class would be acceptable.
An easy and generic example is as follows:
Object o = new Foo();
Since every class extends Object, any object can be
stored in an Object variable.
They just have extra info that can’t be accessed.
Superclass
Subclass

Example
In the bird and parrot example, consider a bird method:
static void printCall(Bird bird) {
System.out.println(bird.call);
}
Generic: printBirdCall expects a Bird, but any type of
bird is OK.
Cannot write Parrot p = new Bird(); //there’s not
enough info!
However, without casting, b can only use bird methods.
Bird b = new Parrot();
printBirdCall(b)
Parrot p = new Parrot();
printBirdCall(p)

Casting and instanceof
If we know that b is a Parrot, we can cast it and use Parrot
methods:
((Parrot)b).speak()
Side note: Ellipse2D.Doubles have x coordinates, Shapes do not:
((Ellipse2D.Double)shape).x += xVelocity;
At runtime, if b is just a Bird, the JVM will throw a
ClassCastException.
To test this, use instanceof:
if (b instanceof Parrot) { ((Parrot)b).speak()) }

Late Binding: The Power of
Polymorphism
Hourly Employee h = new HourlyEmployee("Wilma Worker", new
Date("October", 16, 2005), 12.50, 170);
SalariedEmployee s = new SalariedEmployee("Mark Manager",
new Date("June", 4, 2006), 40000);
Employee e = null;
if (getWeekDay().equals(“Saturday”)
e = h;
else
e = s;
System.out.println(e);
When can I tell which value e will have, at compile time or run time?
So Java defers the decision about which version of toString() will be used until
then: it binds the actual method call used as late as possible.
Late Binding is also called dynamic dispatch or dynamic binding.
Note: it uses the most specific versionof the method it can.

Overriding vs. Overloading
Recall: overriding a method is when a subclass
has method with the same signature (name and
parameter list) as its superclass
Mover’s act() and Bouncer’s act()
Overloadinga method is when two methods
have the same name, but different parameter
lists
Arrays.sort(array, begin, end) and Arrays.sort(array)

Quiz #2
What do you think?

Back to the demo
This part is much shorter.
Make sure you turn in the second quiz.
Tags