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.

Slides:



Advertisements
Similar presentations
Object Oriented Programming with Java
Advertisements

A subclass can add new private instance variables A subclass can add new public, private or static methods A subclass can override inherited methods A.
METHOD OVERRIDING 1.Sub class can override the methods defined by the super class. 2.Overridden Methods in the sub classes should have same name, same.
CS 211 Inheritance AAA.
CS 106 Introduction to Computer Science I 04 / 11 / 2008 Instructor: Michael Eckmann.
Georgia Institute of Technology Workshop for CS-AP Teachers Chapter 3 Advanced Object-Oriented Concepts.
Chapter 8 Inheritance Part 2. © 2004 Pearson Addison-Wesley. All rights reserved8-2 Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance.
Inheritance Inheritance Reserved word protected Reserved word super
ITEC200 – Week03 Inheritance and Class Hierarchies.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 8.1 – 8.5.
INF 523Q Chapter 7: Inheritance. 2 Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
CS102--Object Oriented Programming Lecture 7: – Inheritance Copyright © 2008 Xiaoyan Li.
CSSE221: Software Dev. Honors Day 5 Announcements Announcements Homework 2 written portion due now Homework 2 written portion due now You survived the.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
1 Inheritance and Polymorphism. 2 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Unit 011 Inheritance Recall What Inheritance is About The extends Keyword The Object Class Overriding versus Overloading What is Actually Inherited? Single.
Vocabulary Key Terms polymorphism - Selecting a method among many methods that have the same name. subclass - A class that inherits variables and methods.
(c) University of Washington03-1 CSC 143 Java Inheritance Reading: Ch. 10.
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
CISC6795: Spring Object-Oriented Programming: Polymorphism.
CSE 501N Fall ‘09 15: Polymorphism October 22, 2009 Nick Leidenfrost.
1 Java Inheritance. 2 Inheritance On the surface, inheritance is a code re-use issue. –we can extend code that is already written in a manageable manner.
Java Implementation: Part 3 Software Construction Lecture 8.
Features of Object Oriented Programming Lec.4. ABSTRACTION AND ENCAPSULATION Computer programs can be very complex, perhaps the most complicated artifact.
What is inheritance? It is the ability to create a new class from an existing class.
CSE 501N Fall ‘09 14: Inheritance 20 October 2009 Nick Leidenfrost.
Inheritance and Polymorphism Daniel Liang, Introduction to Java Programming.
Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms Inheritance and Polymorphism.
RIT Computer Science Dept. Goals l Inheritance l Modifiers: private, public, protected l Polymorphism.
OOP: Encapsulation,Abstraction & Polymorphism. What is Encapsulation Described as a protective barrier that prevents the code and data being randomly.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
8. Inheritance “Is-a” Relationship. Topics Creating Subclasses Overriding Methods Class Hierarchies Abstract Class Inheritance and GUIs The Timer Class.
Inheritance and Access Control CS 162 (Summer 2009)
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Inheritance Objectives: Creating new classes from existing classes The protected modifier Creating class hierarchies Abstract classes Indirect visibility.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
Object Oriented Programming
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Coming up: Inheritance
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
(c) University of Washington06-1 CSC 143 Java Inheritance Tidbits.
Georgia Institute of Technology More on Creating Classes part 3 Barb Ericson Georgia Institute of Technology Nov 2005.
Java Software Solutions Lewis and Loftus Chapter 8 Copyright 1997 by John Lewis and William Loftus. All rights reserved. 1 Inheritance -- Introduction.
Object orientation and Packaging in Java Object Orientation and Packaging Introduction: After completing this chapter, you will be able to identify.
Inheritance ndex.html ndex.htmland “Java.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
COP INTERMEDIATE JAVA Inheritance, Polymorphism, Interfaces.
CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 20 – C++ Subclasses and Inheritance.
Fundamentals of Software Development 1Slide 1 Inheritance Key ideas of Inheritance:Key ideas of Inheritance: –Overriding methods –Protected visibility.
Notices Assn 2 is due tomorrow, 7pm. Moodle quiz next week – written in the lab as before. Everything up to and including today’s lecture: Big Topics are.
Lecture 10 – Polymorphism Nancy Harris with additional slides Professor Adams from Lewis & Bernstein.
Lecture 6:Interfaces and Abstract Classes Michael Hsu CSULA.
Modern Programming Tools And Techniques-I
OOP: Encapsulation &Abstraction
Inheritance and Polymorphism
An Introduction to Inheritance
CSC 143 Inheritance.
Chapter 9 Inheritance and Polymorphism
Programming in C# CHAPTER 5 & 6
Presentation transcript:

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 today. Hint on BallWorlds’ changing the x and y coords in 2 nd half of lecture today.

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

Reminder For the inheritance, polymorphism, and array groups, you owe me 3 things: 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 CSSE221 students: Some material from those produced by Fall CSSE221 students: Michael Auchter Michael Auchter Michael Boland Michael Boland Andrew Hettlinger Andrew Hettlinger

Inheritance Objects of different kinds (classes) have their own unique behavior. Objects of different kinds (classes) have their own unique behavior. Objects of different kinds often share similar behavior too. Objects of different kinds often share similar behavior too. For example: For example: Student, Professor, Software Engineer, Chemical Engineer, Physicist, Guitarist, Drummer 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 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? 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. Inheritance allows you to reuse methods that you’ve already written to create more specialized versions of a class. Java keyword: extends. Java keyword: extends. public class HourlyEmployee extends Employee. public class HourlyEmployee extends Employee. We say that an HourlyEmployee IS-A 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). 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. 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? Quiz question: What is the relationship between a parrot and a bird?

Your turn What is the relationship between a parrot and a bird? What is the relationship between a parrot and a bird? Every parrot is a bird, but not every bird is a parrot. Every parrot is a bird, but not every bird is a parrot. So if you had a Java class for each, which class would extend which? So if you had a Java class for each, which class would extend which?

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

Code re-use The subclass inherits all the public and protected methods and fields of the superclass. The subclass inherits all the public and protected methods and fields of the superclass. Constructors are not inherited Constructors are not inherited Constructors can be invoked by the subclass Constructors can be invoked by the subclass Subclass can add new methods and fields. Subclass can add new methods and fields.

Overriding Methods DudThatMoves will “extend” Dud DudThatMoves will “extend” Dud If it defines an act() method with the same signature that overrides Dud’s method 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? 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. Public – Accessible by any other class in any package. Private – Accessible only within the class. Private – Accessible only within the class. Protected – Accessible only by classes within the same package and any subclasses in other packages. 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) (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. Default (No Modifier) – Accessible by classes in the same package but not by classes in other packages. Use sparingly! Use sparingly!

Protected Visibility Suppose in Dud you defined: Suppose in Dud you defined: 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 fields Children can access/modify the fields this.xPos in Dud (parent) and this.xPos in DudThatMoves (child) refer to same value 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”: It’s like the word “this,” only “super”: In a child class, “super” refers to its parent. In a child class, “super” refers to its parent. Two uses: 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 Reminder, still use this (super not needed) to access parent’s fields: this.xPos

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

More examples of super See demo code for examples of: See demo code for examples of: super to call a constructor super to call a constructor super to call a method super to call a method

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. 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. 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. 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. Therefore, super(…) and this(…) cannot be used in the same constructor.

The other use of this in Java Aside from being used to call constructors, this can also be used in Java to specifically reference variables inside of a class. Aside from being used to call constructors, this can also be used in Java to specifically reference variables inside of a class. Here is a code example. Here is a code example. public class foo{ private String theString; public foo (String theString){ this.theString = theString; }} The keyword this is used in this method to differentiate between the String called theString that lives in the class and the String called theString that is passed as an argument.

Final notes Every object in Java extends java.lang.Object Every object in Java extends java.lang.Object Don’t have to say it explicitly Don’t have to say it explicitly This is why every class has a basic toString() method. This is why every class has a basic toString() method. What does it mean for a field to be declared final? What does it mean for a field to be declared final? Final fields can’t be assigned a new value Final fields can’t be assigned a new value Final methods cannot be overridden Final methods cannot be overridden Final classes cannot be extended Final classes cannot 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.

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

Inheritance Demo Be sure you finish the quiz Be sure you finish the quiz Then take a break 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. 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: An easy and generic example is as follows: Object o = new Foo(); Object o = new Foo(); Since every class extends Object, any object can be stored in an Object variable. Since every class extends Object, any object can be stored in an Object variable. They just have extra info that can’t be accessed. They just have extra info that can’t be accessed. Superclass Subclass

Example In the bird and parrot example, consider a bird method: 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. Generic: printBirdCall expects a Bird, but any type of bird is OK. Cannot write Parrot p = new Bird(); //there’s not enough info! Cannot write Parrot p = new Bird(); //there’s not enough info! However, without casting, b can only use bird methods. 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: 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: 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. At runtime, if b is just a Bird, the JVM will throw a ClassCastException. To test this, use instanceof: 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 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() Mover’s act() and Bouncer’s act() Overloading a method is when two methods have the same name, but different parameter lists Overloading a method is when two methods have the same name, but different parameter lists Arrays.sort(array, begin, end) and Arrays.sort(array) Arrays.sort(array, begin, end) and Arrays.sort(array)

Quiz #2 What do you think? What do you think?

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