SlideShare a Scribd company logo
CSSE221: Software Dev. Honors Day 6
 Announcements
 Questions?
 Hint on BallWorlds’ changing the x and y coords in
2nd 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 Employee class and want to
create an HourlyEmployee class that adds
info about wages. Why not copy-and-paste,
then modify?
1. Fixing bugs: what if one were wrong?
2. Maintenance: what if Employee changes?
3. Code-reuse: would code that takes an Employee
as a parameter also take an HourlyEmployee?
The Basics of Inheritance
 Inheritance allows you to reuse methods that
you’ve already written to create more specialized
versions of a class.
 Java keyword: extends.
 public class HourlyEmployee extends Employee.
 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 inherits all the public and
protected methods 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.xPos in Dud (parent) and this.xPos in
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 super may
be passed to super.
The this Keyword
1. this.someField and this.someMethod(): nice style
2. this alone is used to represent the whole object: env.addBall(this)
3. this is 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;
}
}
 this has 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 version of 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()
 Overloading a 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.
Ad

More Related Content

Similar to InheritanceAndPolymorphismprein Java.ppt (20)

OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
Sagar Verma
 
Pi j3.1 inheritance
Pi j3.1 inheritancePi j3.1 inheritance
Pi j3.1 inheritance
mcollison
 
38 object-concepts
38 object-concepts38 object-concepts
38 object-concepts
raahulwasule
 
L02 Software Design
L02 Software DesignL02 Software Design
L02 Software Design
Ólafur Andri Ragnarsson
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
mha4
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
mha4
 
Chap11
Chap11Chap11
Chap11
Terry Yoast
 
38-object-concepts.ppt
38-object-concepts.ppt38-object-concepts.ppt
38-object-concepts.ppt
Ravi Kumar
 
Modules 333333333³3444444444444444444.pptx
Modules 333333333³3444444444444444444.pptxModules 333333333³3444444444444444444.pptx
Modules 333333333³3444444444444444444.pptx
radhikacordise
 
oops -concepts
oops -conceptsoops -concepts
oops -concepts
sinhacp
 
38 object-concepts (1)
38 object-concepts (1)38 object-concepts (1)
38 object-concepts (1)
Shambhavi Vats
 
Chapter5.pptxfghwryhYETHYETH67IOIKUTJJUILOUI
Chapter5.pptxfghwryhYETHYETH67IOIKUTJJUILOUIChapter5.pptxfghwryhYETHYETH67IOIKUTJJUILOUI
Chapter5.pptxfghwryhYETHYETH67IOIKUTJJUILOUI
berihun18
 
Core java oop
Core java oopCore java oop
Core java oop
Parth Shah
 
Delphi qa
Delphi qaDelphi qa
Delphi qa
sandy14234
 
Chapter- 3 Inheritance and Polymorphism-1x4.pdf
Chapter- 3 Inheritance and Polymorphism-1x4.pdfChapter- 3 Inheritance and Polymorphism-1x4.pdf
Chapter- 3 Inheritance and Polymorphism-1x4.pdf
joshua211619
 
Basic object oriented concepts (1)
Basic object oriented concepts (1)Basic object oriented concepts (1)
Basic object oriented concepts (1)
Infocampus Logics Pvt.Ltd.
 
E3
E3E3
E3
lksoo
 
Object oreinted php | OOPs
Object oreinted php | OOPsObject oreinted php | OOPs
Object oreinted php | OOPs
Ravi Bhadauria
 
ACM init() Day 6
ACM init() Day 6ACM init() Day 6
ACM init() Day 6
UCLA Association of Computing Machinery
 
Inheritance in java.ppt
Inheritance in java.pptInheritance in java.ppt
Inheritance in java.ppt
SeethaDinesh
 
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
Sagar Verma
 
Pi j3.1 inheritance
Pi j3.1 inheritancePi j3.1 inheritance
Pi j3.1 inheritance
mcollison
 
38 object-concepts
38 object-concepts38 object-concepts
38 object-concepts
raahulwasule
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
mha4
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
mha4
 
38-object-concepts.ppt
38-object-concepts.ppt38-object-concepts.ppt
38-object-concepts.ppt
Ravi Kumar
 
Modules 333333333³3444444444444444444.pptx
Modules 333333333³3444444444444444444.pptxModules 333333333³3444444444444444444.pptx
Modules 333333333³3444444444444444444.pptx
radhikacordise
 
oops -concepts
oops -conceptsoops -concepts
oops -concepts
sinhacp
 
38 object-concepts (1)
38 object-concepts (1)38 object-concepts (1)
38 object-concepts (1)
Shambhavi Vats
 
Chapter5.pptxfghwryhYETHYETH67IOIKUTJJUILOUI
Chapter5.pptxfghwryhYETHYETH67IOIKUTJJUILOUIChapter5.pptxfghwryhYETHYETH67IOIKUTJJUILOUI
Chapter5.pptxfghwryhYETHYETH67IOIKUTJJUILOUI
berihun18
 
Chapter- 3 Inheritance and Polymorphism-1x4.pdf
Chapter- 3 Inheritance and Polymorphism-1x4.pdfChapter- 3 Inheritance and Polymorphism-1x4.pdf
Chapter- 3 Inheritance and Polymorphism-1x4.pdf
joshua211619
 
Object oreinted php | OOPs
Object oreinted php | OOPsObject oreinted php | OOPs
Object oreinted php | OOPs
Ravi Bhadauria
 
Inheritance in java.ppt
Inheritance in java.pptInheritance in java.ppt
Inheritance in java.ppt
SeethaDinesh
 

More from gayatridwahane (7)

Lecture on Hadoop Technology MCA Engg.ppt
Lecture on Hadoop Technology MCA Engg.pptLecture on Hadoop Technology MCA Engg.ppt
Lecture on Hadoop Technology MCA Engg.ppt
gayatridwahane
 
lecture on Nakamoto Principle document .pptx
lecture on  Nakamoto Principle document .pptxlecture on  Nakamoto Principle document .pptx
lecture on Nakamoto Principle document .pptx
gayatridwahane
 
CEN6070-cproject life cyhcleChapter7.2.ppt
CEN6070-cproject life cyhcleChapter7.2.pptCEN6070-cproject life cyhcleChapter7.2.ppt
CEN6070-cproject life cyhcleChapter7.2.ppt
gayatridwahane
 
The 7 QC Tools Qulaity - English (19 Pages).ppt
The 7 QC Tools Qulaity  - English (19 Pages).pptThe 7 QC Tools Qulaity  - English (19 Pages).ppt
The 7 QC Tools Qulaity - English (19 Pages).ppt
gayatridwahane
 
CMM Capability maturity model for engg.ppt
CMM Capability maturity model for engg.pptCMM Capability maturity model for engg.ppt
CMM Capability maturity model for engg.ppt
gayatridwahane
 
Ch18-MaturityModelsin software engineering.ppt
Ch18-MaturityModelsin software engineering.pptCh18-MaturityModelsin software engineering.ppt
Ch18-MaturityModelsin software engineering.ppt
gayatridwahane
 
introduction to java scriptsfor sym.pptx
introduction to java scriptsfor sym.pptxintroduction to java scriptsfor sym.pptx
introduction to java scriptsfor sym.pptx
gayatridwahane
 
Lecture on Hadoop Technology MCA Engg.ppt
Lecture on Hadoop Technology MCA Engg.pptLecture on Hadoop Technology MCA Engg.ppt
Lecture on Hadoop Technology MCA Engg.ppt
gayatridwahane
 
lecture on Nakamoto Principle document .pptx
lecture on  Nakamoto Principle document .pptxlecture on  Nakamoto Principle document .pptx
lecture on Nakamoto Principle document .pptx
gayatridwahane
 
CEN6070-cproject life cyhcleChapter7.2.ppt
CEN6070-cproject life cyhcleChapter7.2.pptCEN6070-cproject life cyhcleChapter7.2.ppt
CEN6070-cproject life cyhcleChapter7.2.ppt
gayatridwahane
 
The 7 QC Tools Qulaity - English (19 Pages).ppt
The 7 QC Tools Qulaity  - English (19 Pages).pptThe 7 QC Tools Qulaity  - English (19 Pages).ppt
The 7 QC Tools Qulaity - English (19 Pages).ppt
gayatridwahane
 
CMM Capability maturity model for engg.ppt
CMM Capability maturity model for engg.pptCMM Capability maturity model for engg.ppt
CMM Capability maturity model for engg.ppt
gayatridwahane
 
Ch18-MaturityModelsin software engineering.ppt
Ch18-MaturityModelsin software engineering.pptCh18-MaturityModelsin software engineering.ppt
Ch18-MaturityModelsin software engineering.ppt
gayatridwahane
 
introduction to java scriptsfor sym.pptx
introduction to java scriptsfor sym.pptxintroduction to java scriptsfor sym.pptx
introduction to java scriptsfor sym.pptx
gayatridwahane
 
Ad

Recently uploaded (20)

PRIZ Academy - Functional Modeling In Action with PRIZ.pdf
PRIZ Academy - Functional Modeling In Action with PRIZ.pdfPRIZ Academy - Functional Modeling In Action with PRIZ.pdf
PRIZ Academy - Functional Modeling In Action with PRIZ.pdf
PRIZ Guru
 
ZJIT: Building a Next Generation Ruby JIT
ZJIT: Building a Next Generation Ruby JITZJIT: Building a Next Generation Ruby JIT
ZJIT: Building a Next Generation Ruby JIT
maximechevalierboisv1
 
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E..."Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
Infopitaara
 
Artificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptxArtificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptx
aditichinar
 
ISO 9001 quality management systemPPT.pptx
ISO 9001 quality management systemPPT.pptxISO 9001 quality management systemPPT.pptx
ISO 9001 quality management systemPPT.pptx
mesfin608
 
Smart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptxSmart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptx
rushikeshnavghare94
 
Data Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptxData Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptx
RushaliDeshmukh2
 
2025 Apply BTech CEC .docx
2025 Apply BTech CEC                 .docx2025 Apply BTech CEC                 .docx
2025 Apply BTech CEC .docx
tusharmanagementquot
 
Oil-gas_Unconventional oil and gass_reseviours.pdf
Oil-gas_Unconventional oil and gass_reseviours.pdfOil-gas_Unconventional oil and gass_reseviours.pdf
Oil-gas_Unconventional oil and gass_reseviours.pdf
M7md3li2
 
Main cotrol jdbjbdcnxbjbjzjjjcjicbjxbcjcxbjcxb
Main cotrol jdbjbdcnxbjbjzjjjcjicbjxbcjcxbjcxbMain cotrol jdbjbdcnxbjbjzjjjcjicbjxbcjcxbjcxb
Main cotrol jdbjbdcnxbjbjzjjjcjicbjxbcjcxbjcxb
SunilSingh610661
 
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptxLidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
RishavKumar530754
 
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Journal of Soft Computing in Civil Engineering
 
RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdfRICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
MohamedAbdelkader115
 
Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...
Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...
Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...
Journal of Soft Computing in Civil Engineering
 
some basics electrical and electronics knowledge
some basics electrical and electronics knowledgesome basics electrical and electronics knowledge
some basics electrical and electronics knowledge
nguyentrungdo88
 
Dynamics of Structures with Uncertain Properties.pptx
Dynamics of Structures with Uncertain Properties.pptxDynamics of Structures with Uncertain Properties.pptx
Dynamics of Structures with Uncertain Properties.pptx
University of Glasgow
 
Metal alkyne complexes.pptx in chemistry
Metal alkyne complexes.pptx in chemistryMetal alkyne complexes.pptx in chemistry
Metal alkyne complexes.pptx in chemistry
mee23nu
 
New Microsoft PowerPoint Presentation.pdf
New Microsoft PowerPoint Presentation.pdfNew Microsoft PowerPoint Presentation.pdf
New Microsoft PowerPoint Presentation.pdf
mohamedezzat18803
 
Comparing Emerging Cloud Platforms –like AWS, Azure, Google Cloud, Cloud Stac...
Comparing Emerging Cloud Platforms –like AWS, Azure, Google Cloud, Cloud Stac...Comparing Emerging Cloud Platforms –like AWS, Azure, Google Cloud, Cloud Stac...
Comparing Emerging Cloud Platforms –like AWS, Azure, Google Cloud, Cloud Stac...
SiddhiKulkarni18
 
Introduction to Zoomlion Earthmoving.pptx
Introduction to Zoomlion Earthmoving.pptxIntroduction to Zoomlion Earthmoving.pptx
Introduction to Zoomlion Earthmoving.pptx
AS1920
 
PRIZ Academy - Functional Modeling In Action with PRIZ.pdf
PRIZ Academy - Functional Modeling In Action with PRIZ.pdfPRIZ Academy - Functional Modeling In Action with PRIZ.pdf
PRIZ Academy - Functional Modeling In Action with PRIZ.pdf
PRIZ Guru
 
ZJIT: Building a Next Generation Ruby JIT
ZJIT: Building a Next Generation Ruby JITZJIT: Building a Next Generation Ruby JIT
ZJIT: Building a Next Generation Ruby JIT
maximechevalierboisv1
 
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E..."Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
Infopitaara
 
Artificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptxArtificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptx
aditichinar
 
ISO 9001 quality management systemPPT.pptx
ISO 9001 quality management systemPPT.pptxISO 9001 quality management systemPPT.pptx
ISO 9001 quality management systemPPT.pptx
mesfin608
 
Smart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptxSmart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptx
rushikeshnavghare94
 
Data Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptxData Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptx
RushaliDeshmukh2
 
Oil-gas_Unconventional oil and gass_reseviours.pdf
Oil-gas_Unconventional oil and gass_reseviours.pdfOil-gas_Unconventional oil and gass_reseviours.pdf
Oil-gas_Unconventional oil and gass_reseviours.pdf
M7md3li2
 
Main cotrol jdbjbdcnxbjbjzjjjcjicbjxbcjcxbjcxb
Main cotrol jdbjbdcnxbjbjzjjjcjicbjxbcjcxbjcxbMain cotrol jdbjbdcnxbjbjzjjjcjicbjxbcjcxbjcxb
Main cotrol jdbjbdcnxbjbjzjjjcjicbjxbcjcxbjcxb
SunilSingh610661
 
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptxLidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
RishavKumar530754
 
RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdfRICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
MohamedAbdelkader115
 
some basics electrical and electronics knowledge
some basics electrical and electronics knowledgesome basics electrical and electronics knowledge
some basics electrical and electronics knowledge
nguyentrungdo88
 
Dynamics of Structures with Uncertain Properties.pptx
Dynamics of Structures with Uncertain Properties.pptxDynamics of Structures with Uncertain Properties.pptx
Dynamics of Structures with Uncertain Properties.pptx
University of Glasgow
 
Metal alkyne complexes.pptx in chemistry
Metal alkyne complexes.pptx in chemistryMetal alkyne complexes.pptx in chemistry
Metal alkyne complexes.pptx in chemistry
mee23nu
 
New Microsoft PowerPoint Presentation.pdf
New Microsoft PowerPoint Presentation.pdfNew Microsoft PowerPoint Presentation.pdf
New Microsoft PowerPoint Presentation.pdf
mohamedezzat18803
 
Comparing Emerging Cloud Platforms –like AWS, Azure, Google Cloud, Cloud Stac...
Comparing Emerging Cloud Platforms –like AWS, Azure, Google Cloud, Cloud Stac...Comparing Emerging Cloud Platforms –like AWS, Azure, Google Cloud, Cloud Stac...
Comparing Emerging Cloud Platforms –like AWS, Azure, Google Cloud, Cloud Stac...
SiddhiKulkarni18
 
Introduction to Zoomlion Earthmoving.pptx
Introduction to Zoomlion Earthmoving.pptxIntroduction to Zoomlion Earthmoving.pptx
Introduction to Zoomlion Earthmoving.pptx
AS1920
 
Ad

InheritanceAndPolymorphismprein Java.ppt

  • 1. CSSE221: Software Dev. Honors Day 6  Announcements  Questions?  Hint on BallWorlds’ changing the x and y coords in 2nd half of lecture today.
  • 2. 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)
  • 3. Reminder  For the inheritance, polymorphism, and array groups, you owe me 3 things: 1. Summary 2. Quiz 3. Answer key
  • 4. Inheritance slides  Some material from those produced by Fall 2006-2007 CSSE221 students:  Michael Auchter  Michael Boland  Andrew Hettlinger
  • 5. 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
  • 6. Why not just copy-and-paste?  Say I have an Employee class and want to create an HourlyEmployee class that adds info about wages. Why not copy-and-paste, then modify? 1. Fixing bugs: what if one were wrong? 2. Maintenance: what if Employee changes? 3. Code-reuse: would code that takes an Employee as a parameter also take an HourlyEmployee?
  • 7. The Basics of Inheritance  Inheritance allows you to reuse methods that you’ve already written to create more specialized versions of a class.  Java keyword: extends.  public class HourlyEmployee extends Employee.  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.
  • 8. Your turn  Quiz question: What is the relationship between a parrot and a bird?
  • 9. Some Key Ideas in Inheritance  Code reuse  Overriding methods  Protected visibility  The “super” keyword
  • 10. Code re-use  The subclass inherits all the public and protected methods and fields of the superclass.  Constructors are not inherited  Constructors can be invoked by the subclass  Subclass can add new methods and fields.
  • 11. 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!
  • 12. 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!
  • 13. 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.xPos in Dud (parent) and this.xPos in DudThatMoves (child) refer to same value
  • 14. 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
  • 15. 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(); } }
  • 16. 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(); } }
  • 17. 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 super may be passed to super.
  • 18. The this Keyword 1. this.someField and this.someMethod(): nice style 2. this alone is used to represent the whole object: env.addBall(this) 3. this is 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; } }  this has 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.
  • 19. 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.
  • 20. 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)
  • 21. Inheritance Demo  Be sure you finish the quiz  Then take a break
  • 22. 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
  • 23. 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)
  • 24. 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()) }
  • 25. 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 version of the method it can.
  • 26. 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()  Overloading a method is when two methods have the same name, but different parameter lists  Arrays.sort(array, begin, end) and Arrays.sort(array)
  • 27. Quiz #2  What do you think?
  • 28. Back to the demo  This part is much shorter.  Make sure you turn in the second quiz.