CS 112 Introduction to Programming. (Spring 2012)

Similar documents
CS 112 Introduction to Programming

Building Java Programs

CS 112 Introduction to Programming

Admin. CS 112 Introduction to Programming. Admin. Admin. Recap. Recap: Polymorphism and Arrays. the Google doc to record the teaming

CS 112 Introduction to Programming

Admin. q Admin and recap q Class inheritance

Building Java Programs

CSc 110, Spring 2017 Lecture 37: Critters. Adapted from slides by Marty Stepp and Stuart Reges

CSc 110, Spring 2017 Lecture 38: Critters. Adapted from slides by Marty Stepp and Stuart Reges

Admin. CS 112 Introduction to Programming. Recap: OOP Analysis. Software Design and Reuse. Recap: OOP Analysis. Inheritance

Assignment 11: Critters

CS 112 Introduction to Programming

CS 112 Introduction to Programming

Admin. CS 112 Introduction to Programming. Recap: The Critter Class. Recap: Event-Driven Programming. State Machine Driven Cougar.

Overview. Lecture 7: Inheritance and GUIs. Inheritance. Example 9/30/2008

Critters. Critter #2 Attack.ROAR Attack.POUNCE Attack.SCRATCH. Critter #1

CSE 142, Autumn 2018 Programming Assignment #9: Critters (20 points) Due Tuesday, December 4th, 9:00 PM

Topic 31 - inheritance

Lecture 15: Inheritance II

What is Polymorphism? CS 112 Introduction to Programming

Building Java Programs

Critter #1 Attack.ROAR random winner #2 wins #1 wins Attack.POUNCE #1 wins random winner #2 wins Attack.SCRATCH #2 wins #1 wins random winner

CS 112 Introduction to Programming. (Spring 2012)

CS 112 Introduction to Programming. Final Review. Topic: Static/Instance Methods/Variables: I am confused

Homework 9: Critters (cont.)

Recap: Assignment as an Operator CS 112 Introduction to Programming

Programming in C# Inheritance and Polymorphism

CS 112 Introduction to Programming

CSE 142 SPRING 2008 FINAL EXAM

Inheritance. Writing classes. Writing more classes. Why are they very similar? Employee class. Secretary class. Readings: 9.1

Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L

Object Oriented Features. Inheritance. Inheritance. CS257 Computer Science I Kevin Sahr, PhD. Lecture 10: Inheritance

Java Magistère BFA

BBM 102 Introduction to Programming II

Big software. code reuse: The practice of writing program code once and using it in many contexts.

Object Orientated Programming Details COMP360

CISC 3115 TY3. C09a: Inheritance. Hui Chen Department of Computer & Information Science CUNY Brooklyn College. 9/20/2018 CUNY Brooklyn College

Building custom components IAT351

COMPUTER SCIENCE DEPARTMENT PICNIC. Operations. Push the power button and hold. Once the light begins blinking, enter the room code

AP Computer Science. Interactions with superclass

OVERRIDING. 7/11/2015 Budditha Hettige 82

CS 106X Lecture 26: Inheritance and Polymorphism in C++

INHERITANCE. Spring 2019

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

Media Computation. Lecture 16.1, December 8, 2008 Steve Harrison

CmSc 150 Fundamentals of Computing I. Lesson 28: Introduction to Classes and Objects in Java. 1. Classes and Objects

The software crisis. code reuse: The practice of writing program code once and using it in many contexts.

ECE 122. Engineering Problem Solving with Java

ITI Introduction to Computing II

Relationships Between Real Things CSE 143. Common Relationship Patterns. Employee. Supervisor

Class Hierarchy and Interfaces. David Greenstein Monta Vista High School

ITI Introduction to Computing II

Relationships Between Real Things. CSE 143 Java. Common Relationship Patterns. Composition: "has a" CSE143 Sp Student.

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

CS 106B Lecture 27: Inheritance and Polymorphism in C++

Relationships Between Real Things CSC 143. Common Relationship Patterns. Composition: "has a" CSC Employee. Supervisor

Name Return type Argument list. Then the new method is said to override the old one. So, what is the objective of subclass?

CS 112 Introduction to Programming

ECE 122. Engineering Problem Solving with Java

Inheritance and Polymorphism

CSE 143 Lecture 12 Inheritance

The class Object. Lecture CS1122 Summer 2008

Basic Object-Oriented Concepts. 5-Oct-17

Overriding המחלקה למדעי המחשב עזאם מרעי אוניברסיטת בן-גוריון

Abstract Classes and Interfaces

CS-140 Fall 2017 Test 1 Version Practice Practice for Nov. 20, Name:

The Islamic University Gaza Department of Electrical & Computer Engineering. Midterm Exam Spring 2012 Computer Programming II (Java) ECOM 2324

CSE 142 Sample Final Exam #1 (based on Spring 2005's final; thanks to Stuart Reges)

More on Objects in JAVA TM

CIS 110: Introduction to computer programming

Review of Object-Oriented Concepts in JAVA

Overriding Variables: Shadowing

BBM 102 Introduction to Programming II Spring 2017

CLASS DESIGN. Objectives MODULE 4

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.

We are on the GUI fast track path

CS1150 Principles of Computer Science Objects and Classes

Constructor. Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017

8. Polymorphism and Inheritance

Inheritance. Transitivity

Java Inheritance. Written by John Bell for CS 342, Spring Based on chapter 6 of Learning Java by Niemeyer & Leuck, and other sources.

Instance Members and Static Members

Java for Non Majors. Final Study Guide. April 26, You will have an opportunity to earn 20 extra credit points.

Classes and Inheritance Extending Classes, Chapter 5.2

What is Inheritance?

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

Inheritance and Interfaces

The software crisis. code reuse: The practice of writing program code once and using it in many contexts.

Computer Science II (20073) Week 1: Review and Inheritance

Reviewing for the Midterm Covers chapters 1 to 5, 7 to 9. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

AP CS Unit 6: Inheritance Notes

Topic 7: Inheritance. Reading: JBD Sections CMPS 12A Winter 2009 UCSC

Super-Classes and sub-classes

Building Java Programs

Java for Non Majors Spring 2018

The JFrame Class Frame Windows GRAPHICAL USER INTERFACES. Five steps to displaying a frame: 1) Construct an object of the JFrame class

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Procedural programming. [verb-oriented] Tell the computer to do this. (Spring 2012)

CSE 142, Spring 2010 Final Exam Wednesday, June 9, Name: Student ID #: Rules:

Transcription:

CS 112 Introduction to Programming (Spring 2012) Lecture #32: Inheritance and Class Hierarchy Zhong Shao Department of Computer Science Yale University Office: 314 Watson http://flint.cs.yale.edu/cs112 Acknowledgements: some slides used in this class are taken directly or adapted from those accompanying the two textbooks: Introduction to Programming in Java: An Interdisciplinary Approach by Robert Sedgewick and Kevin Wayne and Building Java Programs: A Back to Basics Approach by Stuart Reges and Marty Stepp

super and Constructor q Java constructor automatically inserts super() as the first statement in the constructor of a child class: public class Lawyer extends Employee { public Lawyer() { // super() is automatically inserted System.out.println( In Lawyer() ); public String vacationform() { return "pink"; public int vacationdays() { return super.vacationdays() + 5; public void sue() { System.out.println("I'll see you in court!"); 2

Example public class Lawyer extends Employee { public Lawyer() { // super() is automatically inserted System.out.println( In Lawyer() ); public class Employee { public Employee() { System.out.println( In Employee() ); public static void main(string[] args) { Lawyer larry = new Lawyer(); Output: In Employee() In Lawyer() 3

Exercise: Add name to Employee public class Employee { private String name; public Employee(String name) { this.name = name; 4

Problem with constructors q Now that we've added the constructor to the Employee class, our subclasses do not compile. The error: Lawyer.java:2: cannot find symbol symbol : constructor Employee() location: class Employee public class Lawyer extends Employee { ^ 5

The explanation q Constructors aren't inherited. The Employee subclasses don't inherit the public Employee(String name) constructor. q After defining public Employee(String), Java sees that we have a constructor, and will no longer provide the default Employee constructor. i.e., public Employee() is not defined unless we define it explicitly q But public Lawyer() { // super() is automatically inserted but not defined // in Employee System.out.println( In Lawyer() ); 6

super and Constructor q To pass parameter to parent s constructor, add super( ) as first statement in child s constructor public class Lawyer extends Employee { public Lawyer(String name) { super(name); System.out.println( In Lawyer() ); public class Employee { private String name; public Employee(String name) { System.out.println( In Employee() ); this.name = name; 7

Summary: Method/data Inheritance q Use extends to allow a derived class to access data/methods defined in parent class q A child can override a method defined in the parent class if you do not want a method to be over-ridden, declare it final q Access a method defined in a parent class using super 8

Levels of inheritance Multiple levels of inheritance in a hierarchy are allowed. Example: A legal secretary is the same as a regular secretary but makes more money (10% more) and can file legal briefs. public class LegalSecretary extends Secretary {... Exercise: Complete the LegalSecretary class. 9

LegalSecretary class // A class to represent legal secretaries. public class LegalSecretary extends Secretary { public void filelegalbriefs() { System.out.println("I could file all day!"); public double pay() { return super.pay() * 1.1 ; 10

Partner class q Partner is a senior lawyer that can get bonus. Thus it supports: awardbonus(double bonus) 11

Partner class // A class to represent partner. public class Partner extends Lawyer { private bonus; public void awardbonus(double bonus) { this.bonus = bonus; public double pay() { return super.pay() + bonus ; 12

Class Hierarchies q Many large-scale software systems define class hierarchies, where the root defines the common behaviors Employee Secretary Lawyer Marketer LegalSecretary Partner 13

Class Hierarchies: Another Example Animal Reptile Bird Mammal Snake Lizard Parrot Horse Bat 14

The Object Class q A class called Object is defined in the java.lang package of the Java standard class library q All classes are derived from the Object class even if a class is not explicitly defined to be the child of an existing class, it is assumed to be the child of the Object class the Object class is therefore the ultimate root of all class hierarchies q The Object class contains a few most basic methods, which are inherited by all classes tostring() equals() clone() 15

The Object Class: the tostring Method q That s why the println method can call tostring for any object that is passed to it all objects are guaranteed to have a tostring method via inheritance q The tostring method in the Object class is defined to return a string that contains the name of the object s class and a hash value q Every time we have defined tostring, we have actually been overriding it 16

Example: GUI Component Class Hierarchy q A Java GUI component is an object that represents a visual entity in a graphical user interface (such as a button, a label, or slider) q Component classes are organized into an inheritance hierarchy so that they can easily share characteristics q A derived component class overrides the method defined in the ancestor class to define its own visual display e.g., different component classes redefine the paintcomponent method to display differently 17

Class Hierarchy (A Very Small Subset) Component paint() Container JComponent paintcomponent() JPanel JAbstractButton JLabel JTextComponent JButton JToggleButton JTextField JCheckBox JRadioBox 18

Using Java GUI Components q Java GUI manager maintains a collection of GUI components and delivers events (e.g., to draw, to respond to a click) to components Each component provides callback functions for the manager to invoke This is called event driven programming 19

Assignment 9 Class Hierarchy Critter Ant Bird Hippo Bulldog Vulture 20

Critter : Cougar Method constructor public Cougar() eat public class Cougar extends Critter {... fight getcolor Always eats. Always pounces. Behaviors to Override Blue if the Cougar has never fought; red if he has. getmove tostring Walks west until he finds food; then walks east until he finds food; then goes west and repeats. "C"

getcolor for Cougar q State machine fight()! Has fought Has fought q How to remember the state? a boolean instance variable: boolean fought q What is initial state and where to set it? In constructor: fought = false; q Who/when updates the state? In fight(): fought = true 22

getmove for Cougar q State machine eat() Move West Move East eat() q How to remember the state? a boolean instance variable: boolean west q What is initial state and where to set it? In constructor: west = true; q Who/when updates the state? In eat(): reverse state 23

Cougar solution import java.awt.*; // for Color public class Cougar extends Critter { private boolean west; private boolean fought; public Cougar() { west = true; fought = false; public boolean eat() { west =!west; return true; public Attack fight(string opponent) { fought = true; return Attack.POUNCE;...

Cougar solution... public Color getcolor() { if (fought) { return Color.RED; else { return Color.BLUE; public Direction getmove() { if (west) { return Direction.WEST; else { return Direction.EAST; public String tostring() { return "C";

Critter : Snake Method Behavior constructor public Snake() eat Never eats fight always forfeits getcolor black getmove 1 E, 1 S; 2 W, 1 S; 3 E, 1 S; 4 W, 1 S; 5 E,... tostring "S"

Determining necessary fields q Information required to decide what move to make? Direction to go Length of current cycle Number of moves made in current cycle

Determining necessary fields A non-event driven version

Determining necessary fields A non-event driven version cycle = 1; while (true) { for (steps = 0; steps < cyclelength; step++) go S if cyclelength % 2 == 1 go E else go W cyclelength ++

Guarding Condition A non-event driven version steps < cyclelength cycle = 1; while (true) { for (steps = 0; steps < cyclelength; steps++) if cyclelength % 2 == 1 go East else go South go West cyclelength ++ if (cyclelength % 2 == 1) go East else go West steps++; steps == cyclelength go South cyclelength ++ steps=0; 30

Snake solution import java.awt.*; // for Color public class Snake extends Critter { private int cyclelength; // # steps in curr. Horiz. cycle private int steps; // # of cycle's steps already taken steps < cyclelength public Snake() { cyclelength = 1; steps = 0; public Direction getmove() { if (steps < cyclelength) { steps++; if (cyclelength % 2 == 1) { return Direction.EAST; else { return Direction.WEST; else { steps = 0; cyclelength ++; return Direction.SOUTH; public String tostring() { return "S"; if (cyclelength % 2 == 1) go East else go West steps++; steps == cyclelength Go South cyclelength ++ steps=0;

Comment: States q Counting is helpful: How many total moves has this animal made? How many times has it eaten? Fought? q Remembering recent actions in fields may be helpful: Which direction did the animal move last? How many times has it moved that way? Did the animal eat the last time it was asked? How many steps has the animal taken since last eating? How many fights has the animal been in since last eating?

Testing critters q Focus on one specific critter of one specific type Only spawn 1 of each animal, for debugging q Make sure your fields update properly Use println statements to see field values q Look at the behavior one step at a time Use "Tick" rather than "Go"

Designing Bulldog q Be open minded q Think about strategies, e.g., How much state do your bulldogs keep and probe state (e.g., do your bulldogs work together to map the world?) Do your bulldogs play strategic games (e.g., bluffing)? Do your bulldogs coordinate their behaviors to form some kind of patterns? 34

Coordination 35

Coordination 36

Comment: Class/Static Variables q Sometimes it might be useful if all object instances of a class share the same copy of a variable, e.g., common constant variables global statistics coordination q Declare variables using keyword static to create only one copy of the variable q Such variables are called static or class variables q Class/static variables are accessible by all methods in the class 37

Example: Keeping Track of Employee Objects q We want to keep track of the number of Employee objects we ever created q In our Employee class, we could add the following data: static int counter, an integer that represents the number of accounts we ever created since counter is static, it is shared by all account objects in constructor, we increase counter by 1 38

Employee with Static public class Employee { private String name; private static int counter = 0; public Employee(String name) { this.name = name; counter++; public static int nemployees() { return counter; public class Firm { public static void main(string[] args) { Lawyer larry = new Lawyer( Larry"); Marketer mike = new Marketer("Mike"); Partner peter = new Partner("Peter");

Example: The Employee Objects 0 Employee.counter 40

Example: The Employee Objects larry: Lawyer name = Larry 10 Employee.counter After Lawyer larry = new Lawyer("Larry"); 41

Example: The Employee Objects larry: Lawyer name = Larry 21 Employee.counter mike: Marketer name = Mike After Marketer mike = new Marketer("Mike"); 42

Example: The Employee Objects larry: Lawyer name = Larry 32 Employee.counter mike: Marketer name = Mike peter: Partner name = Peter bonus = 0 After Partner peter = new Partner("Peter"); 43