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

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

Dec 19, 2015

Download

Documents

Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: CSSE221: Software Dev. Honors Day 6 Announcements Announcements Questions? Questions? Hint on BallWorlds’ changing the x and y coords in 2 nd half of lecture.

CSSE221: Software Dev. Honors CSSE221: Software Dev. Honors Day 6Day 6 AnnouncementsAnnouncements

Questions?Questions? Hint on BallWorlds’ changing the x and Hint on BallWorlds’ changing the x and

y coords in 2y coords in 2ndnd half of lecture today. half of lecture today.

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

This week: BallWorlds This week: BallWorlds assignmentassignment

Monday:Monday: Intro to UML as a communication toolIntro to UML as a communication tool Writing methods you don't callWriting methods you don't call Using Using thisthis

Tuesday:Tuesday: InheritanceInheritance PolymorphismPolymorphism

Thursday:Thursday: Introducing next week’s assignment Introducing next week’s assignment Arrays and ArrayListsArrays and ArrayLists (Using the debugger)(Using the debugger)

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

ReminderReminder

For the inheritance, polymorphism, For the inheritance, polymorphism, and array groups, you owe me 3 and array groups, you owe me 3 things:things:

1.1. SummarySummary

2.2. QuizQuiz

3.3. Answer keyAnswer key

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

Inheritance slidesInheritance slides

Some material from those produced Some material from those produced by Fall 2006-2007 CSSE221 by Fall 2006-2007 CSSE221 students:students: Michael AuchterMichael Auchter Michael BolandMichael Boland Andrew HettlingerAndrew Hettlinger

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

InheritanceInheritance

Objects of different kinds (classes) have Objects of different kinds (classes) have their own unique behavior. their own unique behavior.

Objects of different kinds often Objects of different kinds often share share similar behavior too.similar behavior too.

For example:For example: Student, Professor, Software Engineer, Student, Professor, Software Engineer,

Chemical Engineer, Physicist, Guitarist, Chemical Engineer, Physicist, Guitarist, DrummerDrummer

Each has distinct actions to perform, but Each has distinct actions to perform, but they also have many features and behavior they also have many features and behavior in commonin common

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

Why not just copy-and-Why not just copy-and-paste?paste?

Say I have an Say I have an EmployeeEmployee class and class and want to create an want to create an HourlyEmployeeHourlyEmployee class that adds info about wages. Why class that adds info about wages. Why not copy-and-paste, then modify?not copy-and-paste, then modify?

1.1. Fixing bugs: what if one were wrong?Fixing bugs: what if one were wrong?

2.2. Maintenance: what if Maintenance: what if EmployeeEmployee changes? changes?

3.3. Code-reuse: would code that takes an Code-reuse: would code that takes an EmployeeEmployee as a parameter also take an as a parameter also take an HourlyEmployeeHourlyEmployee??

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

The Basics of The Basics of InheritanceInheritance

Inheritance allows you to Inheritance allows you to reusereuse methods methods that you’ve already written to create more that you’ve already written to create more specialized versions of a class.specialized versions of a class.

Java keyword: Java keyword: extendsextends.. public class HourlyEmployee public class HourlyEmployee extendsextends

Employee.Employee. We say that an HourlyEmployee We say that an HourlyEmployee IS-A IS-A EmployeeEmployee

Employee is said to be the parent class (or Employee is said to be the parent class (or superclasssuperclass), and HourlyEmployee is called ), and HourlyEmployee is called a child class (or a child class (or subclasssubclass).).

HourlyEmployee receives copies of all of HourlyEmployee receives copies of all of the non-private methods and variables the non-private methods and variables present in Employee.present in Employee.

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

Your turnYour turn

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

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

Some Key Ideas in Some Key Ideas in InheritanceInheritance

Code reuseCode reuse Overriding methodsOverriding methods Protected visibility Protected visibility The “super” keywordThe “super” keyword

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

Code re-useCode re-use

The subclass The subclass inheritsinherits all the all the publicpublic and and protectedprotected methods and fields of methods and fields of the superclass.the superclass. Constructors are not inheritedConstructors are not inherited Constructors can be invoked by the Constructors can be invoked by the

subclasssubclass Subclass can add new methods and Subclass can add new methods and

fields.fields.

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

Overriding MethodsOverriding Methods

DudThatMoves will “extend” DudDudThatMoves will “extend” Dud If it defines an If it defines an act()act() method with the method with the

same signature that same signature that overrides overrides Dud’s Dud’s methodmethod

What do you think happens if our What do you think happens if our child class doesn’t override a method child class doesn’t override a method in the parent class?in the parent class?

It’s exactly the same as in the parent class!

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

Visibility ModifiersVisibility Modifiers• PublicPublic – Accessible by any other class in any – Accessible by any other class in any

package.package.

• PrivatePrivate – Accessible only within the class. – Accessible only within the class.

• ProtectedProtected – Accessible only by classes within – Accessible only by classes within the same package and any subclasses in other the same package and any subclasses in other packages.packages.• (For this reason, some choose not to use protected, (For this reason, some choose not to use protected,

but use private with accessors) but use private with accessors)

• Default (No Modifier) – Accessible by classes in Default (No Modifier) – Accessible by classes in the same package but not by classes in other the same package but not by classes in other packages.packages.• Use sparingly!Use sparingly!

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

Protected VisibilityProtected Visibility

Suppose in Dud you defined:Suppose in Dud you defined:

protected int xPos;protected int xPos; Then:Then:

Instances of children inherit this field Instances of children inherit this field (one for each instance)(one for each instance)

Children can access/modify the fieldsChildren can access/modify the fields this.xPosthis.xPos in Dud (parent) and in Dud (parent) and

this.xPosthis.xPos in DudThatMoves (child) in DudThatMoves (child) refer to same valuerefer to same value

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

The “super” KeywordThe “super” Keyword It’s like the word “this,” only “super”:It’s like the word “this,” only “super”: In a child class, “super” refers to its In a child class, “super” refers to its

parent.parent. Two uses:Two uses:

1.1. To call a parent’s method, use To call a parent’s method, use super.super.methodNamemethodName(…)(…)

2.2. To call a parent’s constructor, use To call a parent’s constructor, use super(some super(some parameter)parameter)from the child class’from the child class’ constructor constructor

Reminder, still use Reminder, still use this this (super not needed) (super not needed) to access parent’s fields: to access parent’s fields: this.xPosthis.xPos

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

The “super” KeywordThe “super” Keyword

Methods can call Methods can call super.super.methodNamemethodName(…)(…) To do the work of the parent class To do the work of the parent class

method, plus…method, plus… Additional work for the child classAdditional work for the child class

public class Workaholic extends Worker { public void doWork() { super.doWork();

drinkCoffee(); super.doWork(); }

}

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

The “super” KeywordThe “super” Keyword

Methods can call Methods can call super.super.methodNamemethodName(…)(…) To do the work of the parent class To do the work of the parent class

method, plus…method, plus… Additional work for the child classAdditional work for the child class

public class RoseStudent extends Worker { public void doWork() { while (!isCollapsed) { super.doWork();

drinkCoffee(); }

super.doWork(); }}

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

Rules of using Rules of using super super in in constructorsconstructors

A A super(…)super(…) call must be the first call must be the first line of the code of an object’s line of the code of an object’s constructor if it is to be used.constructor if it is to be used.

Instance variables cannot be passed Instance variables cannot be passed along with the along with the super(…)super(…) call. Only call. Only variables that are passed to the variables that are passed to the constructor that calls constructor that calls supersuper may be may be passed to passed to supersuper..

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

The The thisthis Keyword Keyword1.1. this.someFieldthis.someField and and this.someMethod()this.someMethod(): nice style: nice style2.2. thisthis alone is used to represent the whole object: alone is used to represent the whole object:

env.addBall(this)env.addBall(this)3.3. thisthis is used to call another constructor inside of a is used to call another constructor inside of a

method with multiple constructors.method with multiple constructors.

public class foo {public class foo {private String message;private String message;

public foo(){ public foo(){ this(“This foo is saaaaaad.”);this(“This foo is saaaaaad.”);

}}public foo(String s){ public foo(String s){

message = s;message = s;}}

}} thisthis has the same restrictions on it as has the same restrictions on it as supersuper – that is, – that is,

it must be the first thing called in a constructor and it it must be the first thing called in a constructor and it cannot be passed instance variables.cannot be passed instance variables.

Therefore, Therefore, super(…)super(…) and and this(…)this(…) cannot be used in the cannot be used in the same constructor.same constructor.

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

Final notesFinal notes Every Every object in Java extends java.lang.Objectobject in Java extends java.lang.Object

Don’t have to say it explicitlyDon’t have to say it explicitly This is why every class has a basic toString() This is why every class has a basic toString()

method.method. What does it mean for a field to be declared What does it mean for a field to be declared

finalfinal?? Final fields Final fields can’t be assigned a new valuecan’t be assigned a new value Final methods Final methods cannot be overriddencannot be overridden Final classes Final classes cannot be extendedcannot be extended

There is only single inheritance in Java.There is only single inheritance in Java. Subclass can be derived only from one superclass.Subclass can be derived only from one superclass.

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

Inheritance BasicsInheritance Basics(a checklist to which to refer)(a checklist to which to refer)

Classes extending other classes:Classes extending other classes: Only have to describe how they are different from Only have to describe how they are different from

parentsparents Don’t have to repeat methods which Don’t have to repeat methods which are are “good enough” in the “good enough” in the

parentparent Can replace Can replace or or “extend” any method which “extend” any method which isn’t isn’t “good “good

enough”enough” Can access parent’s methods and constrcutors via Can access parent’s methods and constrcutors via

supersuper.. Can share fields with a parent in a “protected” way Can share fields with a parent in a “protected” way

(say, this.xPos)(say, this.xPos) Only need to declare imports they use (like Only need to declare imports they use (like

java.awt.Color)java.awt.Color) Don’t have to redeclare interfaces of the parent (like Don’t have to redeclare interfaces of the parent (like

Drawable)Drawable)

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

Inheritance DemoInheritance Demo

Be sure you finish the quizBe sure you finish the quiz

Then take a breakThen take a break

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

PolymorphismPolymorphism

Polymorphism is the concept of allowing a Polymorphism is the concept of allowing a reference to a subclass to be used in a reference to a subclass to be used in a place where a reference to its parent’s place where a reference to its parent’s class would be acceptable.class would be acceptable.

An easy and generic example is as follows:An easy and generic example is as follows: Object o = new Foo();Object o = new Foo();

Since every class extends Object, any Since every class extends Object, any object can be stored in an Object variable.object can be stored in an Object variable.

They just have extra info that can’t be They just have extra info that can’t be accessed.accessed.

Superclass Subclass

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

ExampleExample In the bird and parrot example, consider a bird In the bird and parrot example, consider a bird

method:method:static void printCall(Bird bird) {static void printCall(Bird bird) {

System.out.println(bird.call);System.out.println(bird.call);

}}

Generic: printBirdCall expects a Bird, but any Generic: printBirdCall expects a Bird, but any type of bird is OK. type of bird is OK.

Cannot Cannot write Parrot p = new Bird(); //there’s not write Parrot p = new Bird(); //there’s not enough info!enough info!

However, without casting, b can only use bird However, without casting, b can only use bird methods.methods.

Bird b = new Parrot();Bird b = new Parrot();printBirdCall(b)printBirdCall(b)Parrot p = new Parrot();Parrot p = new Parrot();printBirdCall(p)printBirdCall(p)

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

Casting and Casting and instanceofinstanceof

If we know that b is a Parrot, we can cast it and If we know that b is a Parrot, we can cast it and use Parrot methods:use Parrot methods:((Parrot)b).speak()((Parrot)b).speak()

Side note: Ellipse2D.Doubles have x coordinates, Side note: Ellipse2D.Doubles have x coordinates, Shapes do not:Shapes do not:((Ellipse2D.Double)shape).x += xVelocity;((Ellipse2D.Double)shape).x += xVelocity;

At runtime, if b is just a Bird, the JVM will throw At runtime, if b is just a Bird, the JVM will throw a ClassCastException.a ClassCastException.

To test this, use instanceof:To test this, use instanceof:if (b instanceof Parrot) { ((Parrot)b).speak()) }if (b instanceof Parrot) { ((Parrot)b).speak()) }

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

Late Binding: Late Binding: The Power of The Power of PolymorphismPolymorphism

Hourly Employee h = new HourlyEmployee("Wilma Worker", new Hourly Employee h = new HourlyEmployee("Wilma Worker", new Date("October", 16, 2005), 12.50, 170);Date("October", 16, 2005), 12.50, 170);

SalariedEmployee s = new SalariedEmployee("Mark Manager", SalariedEmployee s = new SalariedEmployee("Mark Manager", new Date("June", 4, 2006), 40000);new Date("June", 4, 2006), 40000);

Employee e = null;Employee e = null;if (getWeekDay().equals(“Saturday”)if (getWeekDay().equals(“Saturday”)

e = h;e = h;elseelse

e = s;e = s;System.out.println(e);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.

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

Overriding vs. Overriding vs. OverloadingOverloading

Recall: Recall: overriding overriding a method is when a a method is when a subclass has method with the same subclass has method with the same signature (name and parameter list) as signature (name and parameter list) as its superclassits superclass Mover’s act() and Bouncer’s act()Mover’s act() and Bouncer’s act()

OverloadingOverloading a method is when two a method is when two methods have the same name, but methods have the same name, but different parameter listsdifferent parameter lists Arrays.sort(array, begin, end) and Arrays.sort(array, begin, end) and

Arrays.sort(array) Arrays.sort(array)

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

Quiz #2Quiz #2

What do you think?What do you think?

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

Back to the demoBack to the demo

This part is much shorter.This part is much shorter. Make sure you turn in the second Make sure you turn in the second

quiz.quiz.