Chap 7 - Inheritance. An example from Zoology. An example from java.lang. Other terms from inheritance. parent. Mammal. child. Mouse. child.



Similar documents
Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

Yosemite National Park, California. CSE 114 Computer Science I Inheritance

Java Interview Questions and Answers

java Features Version April 19, 2013 by Thorsten Kracht

CS 111 Classes I 1. Software Organization View to this point:

Chapter 13 - Inheritance

AP Computer Science Java Subset

Agenda. What is and Why Polymorphism? Examples of Polymorphism in Java programs 3 forms of Polymorphism

Inheritance, overloading and overriding

Cohort: BCA/07B/PT - BCA/06/PT - BCNS/06/FT - BCNS/05/FT - BIS/06/FT - BIS/05/FT - BSE/05/FT - BSE/04/PT-BSE/06/FT

Java Interfaces. Recall: A List Interface. Another Java Interface Example. Interface Notes. Why an interface construct? Interfaces & Java Types

JAVA - INHERITANCE. extends is the keyword used to inherit the properties of a class. Below given is the syntax of extends keyword.

Introduction to Java. CS 3: Computer Programming in Java

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Java Programming Language

CS1002: COMPUTER SCIENCE OO MODELLING & DESIGN: WEEK 5

J a v a Quiz (Unit 3, Test 0 Practice)

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Implementation Aspects of OO-Languages

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

C++ INTERVIEW QUESTIONS

Part I. Multiple Choice Questions (2 points each):

Advanced Data Structures

History OOP languages Year Language 1967 Simula Smalltalk

Java CPD (I) Frans Coenen Department of Computer Science

The Interface Concept

Two-Dimensional Arrays. Multi-dimensional Arrays. Two-Dimensional Array Indexing

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

Part 3: GridWorld Classes and Interfaces

Preet raj Core Java and Databases CS4PR. Time Allotted: 3 Hours. Final Exam: Total Possible Points 75

Java Application Developer Certificate Program Competencies

Arrays in Java. Working with Arrays

C++FA 5.1 PRACTICE MID-TERM EXAM

Contents. 9-1 Copyright (c) N. Afshartous

Programming Language Concepts: Lecture Notes

CS506 Web Design and Development Solved Online Quiz No. 01

CS170 Lab 11 Abstract Data Types & Objects

SE 360 Advances in Software Development Object Oriented Development in Java. Polymorphism. Dr. Senem Kumova Metin

You are to simulate the process by making a record of the balls chosen, in the sequence in which they are chosen. Typical output for a run would be:

Introduction to Java

Introducing Variance into the Java Programming Language DRAFT

Compiling Object Oriented Languages. What is an Object-Oriented Programming Language? Implementation: Dynamic Binding

Problem 1. CS 61b Summer 2005 Homework #2 Due July 5th at the beginning of class

Iteration CHAPTER 6. Topic Summary

Chapter 2 Introduction to Java programming

CSE 1020 Introduction to Computer Science I A sample nal exam

Java (12 Weeks) Introduction to Java Programming Language

Class 16: Function Parameters and Polymorphism

Chapter 2: Elements of Java

Pemrograman Dasar. Basic Elements Of Java

Java Basics: Data Types, Variables, and Loops

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

Description of Class Mutation Mutation Operators for Java

Basic Programming and PC Skills: Basic Programming and PC Skills:

Debugging. Common Semantic Errors ESE112. Java Library. It is highly unlikely that you will write code that will work on the first go

D06 PROGRAMMING with JAVA

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

How To Write A Program In Java (Programming) On A Microsoft Macbook Or Ipad (For Pc) Or Ipa (For Mac) (For Microsoft) (Programmer) (Or Mac) Or Macbook (For

Object Oriented Software Design

arrays C Programming Language - Arrays

Computer Programming I

The Sun Certified Associate for the Java Platform, Standard Edition, Exam Version 1.0

The Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1

Smallest Java Package? Java.applet.* having 1 class and 3 interfaces. Applet Class and AppletContext, AppletStub, Audioclip interfaces.

Designing with Exceptions. CSE219, Computer Science III Stony Brook University

CS193j, Stanford Handout #10 OOP 3

Introduction to Data Structures

Exception Handling. Overloaded methods Interfaces Inheritance hierarchies Constructors. OOP: Exception Handling 1

Java Programming Fundamentals

Programmation 2. Introduction à la programmation Java

An Incomplete C++ Primer. University of Wyoming MA 5310

Polymorphism. Problems with switch statement. Solution - use virtual functions (polymorphism) Polymorphism

Variables, Constants, and Data Types

Java Cheatsheet. Tim Coppieters Laure Philips Elisa Gonzalez Boix

public static void main(string[] args) { System.out.println("hello, world"); } }

15-214: Principles of Software Construction 8 th March 2012

Sources: On the Web: Slides will be available on:

Arrays. Atul Prakash Readings: Chapter 10, Downey Sun s Java tutorial on Arrays:

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

Software Testing. Definition: Testing is a process of executing a program with data, with the sole intention of finding errors in the program.

Abstract Class & Java Interface

Habanero Extreme Scale Software Research Project

Moving from CS 61A Scheme to CS 61B Java

Object-Oriented Programming

CSCI 253. Object Oriented Programming (OOP) Overview. George Blankenship 1. Object Oriented Design: Java Review OOP George Blankenship.

Part 1 Foundations of object orientation

A Scala Tutorial for Java programmers

Glossary of Object Oriented Terms

Introduction to Java Lecture Notes. Ryan Dougherty

Stack Allocation. Run-Time Data Structures. Static Structures

Statements and Control Flow

Sample CSE8A midterm Multiple Choice (circle one)

Example of a Java program

Transcription:

Chap 7 - Inheritance An example from Zoology parent Mammal child child Mouse Elephant grandchild grandchild grandchild grandchild Field??? African Indian 1 2 An example from java.lang Other terms from inheritance Object Super class/type Number String Derived class Subtype Long Integer Double Float 3 4 //Person.java - characteristics common to all people class Person { Person(String name) { this.name = name; void setage(int age) { this.age = age; void setgender(char gender){ this.gender = gender; void setname(string name) { this.name = name; int getage() { return age; char getgender() { return gender; String getname() { return name; public String tostring() { return ("Name: " + name + ", Age: " + age + ", Gender: " + gender); private String name; private int age; private char gender; //male == M, female == F 5 //Student.java - an example subclass class Student extends Person { Student(String name) { super(name); void setcollege(string college) { this.college = college; void setgpa(double gpa) { this.gpa = gpa; void setyear(byte year) { this.year = year; String getcollege() { return college; double getgpa() { return gpa; byte getyear() { return year; public String tostring() { return(super.tostring() + "\n " + "College: " + college + ", GPA: " + gpa + ", Year: " + year); 6 1

static final byte FROSH = 1; static final byte SOPH = 2; static final byte JUNIOR = 3; static final byte SENIOR = 4; private String college = "Unknown"; private byte year; // FROSH, SOPH, private double gpa; //. to 4. //StudentTest.java class StudentTest { Student student = new Student("Jane Programmer"); student.setage(21); student.setgender( F ); student.setcollege("ucsc"); student.setyear(student.frosh); student.setgpa(3.75f); System.out.println(student.toString()); 7 8 Subtype Principle Methods defined in one class may be redefined in a subclass. This is called method overriding. A subclass object can always be used where an object of its superclass is expected. Treating a subclass object as a superclass object can only remove capabilities, not add them. With inheritance, new methods are Which tostring() gets called? class StudentTest { Student student = new Student("Jane Programmer"); student.setage(21); student.setgender( F ); student.setcollege("ucsc"); student.setyear(student.frosh); student.setgpa(3.75f); System.out.println(student.toString()); Person anyperson = studetn; System.out.println(anyPerson.toString()); added in the subclass, never taken away. 9 1 Can t use Student fields from Person reference class StudentTest { Student student = new Student("Jane Programmer"); student.setage(21); System.out.println(student.toString()); Person anyperson; if (Console.in.readInt() == 1) anyperson = student; else anyperson = new Person("John Doe"); anyperson.setyear(student.frosh); // illegal System.out.println(anyPerson.toString()); 11 Overriding vs Overloading Overloading is when you define two methods with the same name, in the same class, distinguished by their signatures. Overriding is when you redefine a method that has already been defined in a parent class (using the exact same signature). Overloading is resolved at compile time. Overriding is resolved at runtime (based on 12 the type of the implicit first parameter). 2

Dynamic Method Dispatch Determing at runtime, which overriden method to call, is called dynamic method dispatch. This is what allows println() to work with any object. tostring() is defined in Object (the parent of all classes). If you override tostring(), then inside of println(), a call to printthis.tostring(), will get to YOUR tostring(). 13 public class PrintWriter { public void println(object obj) { String s = obj.tostring(); // somehow get the string s printed 14 Dynamic Method Dispatch //SuperClass.java - a sample super class class SuperClass { public void print() { System.out.println( " inside SuperClass"); //SubClass.java - a subclass of SuperClass class SubClass extends SuperClass { public void print() { System.out.println( " inside SubClass"); 15 //TestInherit.java - overridden method selection. class TestInherit { SuperClass s = new SuperClass(); s.print(); s = new SubClass(); s.print(); 16 Access Modifiers, Method Overriding and the Subtype Principle Generic Methods When you override a method you cannot restrict access more than was done with the inherited method. Doing so would break the subtype principle. For example, if class Student overrode tostring() to be private, then System.out.println(anyPerson.toString()); would fail if anyperson was referring to a A generic method is a method that can operate on at least two different types of data. This is a form of polymorphism. println(object obj) is a generic method. It works for any Java reference type. In addition to tostring(), the class Object defines a method public boolean equals(object obj); Student. 17 18 3

Method equals() in Object By overriding equals() we can write a generic methods that need to check if two objects are equal. //Count the number of times obj is found in array. static int howmanycopiesof(object obj, Object[] array) { int count = ; for (int i = ; i < array.length; i++) if (obj.equals(array[i])) count++; return count; 19 2 class EqualsTest { // Create and fill an array of Strings String[] stringarray = new String[1]; for (int i = ; i < stringarray.length; i++) stringarray[i] = "String " + i; // Create and fill an array of Counters Counter[] counterarray = new Counter[5]; for (int i = ; i < counterarray.length; i++) counterarray[i] = new Counter(); // Make two entries refer to the same Counter counterarray[2] = counterarray[]; When equals are not equal? Using the original Counter from chapter 6, the output of the previous program is 2 and 1. That's 2 Counters "equal" to counterarray[], and 1 String "equal" to "String 1". The class String, overrides equals() to compare the characters in two Strings. Counter uses the default equals() which just checks if the references point to the same System.out.println( howmanycopiesof(counterarray[], counterarray)); System.out.println( howmanycopiesof("string 1", stringarray)); 21 object. 22 counterarray[2] = counterarray[]; counterarray Counter objects Primitive Wrapper Classes Object Number Long Integer Double Float counterarray[2].equals(counterarray[]) is true 23 24 4

A Generic Numeric Method Abstract Classes static Number elementmin(number[] array) { Number min = array[]; for (int i = 1; i < array.length; i++) if (array[i].doublevalue() < min.doublevalue()) min = array[i]; return min; This works so long as the loss of precision in coverting to double doesn t affect the selected minimum. 25 An abstract class is use to derive other (concrete) classes. An abstract class usually provides some complete method definitions, but leaves some undefined, requiring all subclasses to provide definitions for the undefined methods. 26 abstract public class AbstractCounter { abstract public void click(); public int get() { return value; public void set(int x) { value = x; public String tostring() { return String.valueOf(value); protected int value; public class Counter extends AbstractCounter { public void click() { value = (value + 1) % 1; 27 public class CountByTwo extends AbstractCounter { public void click() { value = (value + 2) % 1; void samplemethod(abstractcounter counter) { counter.click(); You can declare variables/parameters of abstract types. You cannot ever actually create an object of an abstract class. E.g. new AbstractCounter() is illegal. 28 class Timer extends AbstractCounter { public Timer(int v) { set(v); public void click() { value++; seconds = value % 6; minutes = value / 6; public void set(int v) { value = v; seconds = v % 6; minutes = v / 6; public String tostring() { return minutes + " minutes, " + seconds + " seconds"; private int seconds, minutes; You can, of course, override any of the methods inherited from an abstract class. 29 Predator-Prey: An abstract class A simple simulation of an artificial ecology Object Living Fox Rabbit Grass 3 5

Pseudocode for Predator-Prey create two worlds, current and next initialize one with some life forms print the intial world for each step of the simulation update next based on current print the next world swith the roles of current and next 31 class PredatorPrey { World odd = new World(1), even = new World(1); int i, cycles = 1; even.eden(); //generate initial World System.out.println(even); //print initial state for (i = ; i < cycles; i++) { System.out.println("Cycle = " + i + "\n\n"); if (i % 2 == 1) { even.update(odd); System.out.println(even); else { odd.update(even); System.out.println(odd); 32 Counting Neighbors //Living.java - the superclass for all life forms abstract class Living { Life and death of life forms depends upon the number of various life forms in adjacent cells. Doing this counting is the same for all life forms so we will implement it in an abstract class, Living. Pseudocode set the count for all life form types to for each of the current cells 8 immediate neighbors if the neighbor is type LifeType abstract Count getcount(); abstract Living next(world world); abstract char tochar(); // character for this form void computeneighbors(world world) { world.clearneighborcounts(); world.cells[row][column].getcount().set(-1); for (int i = -1; i <= 1; i++) for (int j = -1; j <= 1; j++) world.cells[row+i][column+j].getcount().inc(); int row, column; //location then increment the count for LifeType 33 34 class Fox extends Living { Fox(int r, int c, int a ) { row = r; column = c; age = a; Living next(world world) { computeneighbors(world); if (Fox.neighborCount.get() > 5 ) //too many Foxes return new Empty(row, column); else if (age > LIFE_EXPECTANCY) //Fox is too old return new Empty(row, column); else if (Rabbit.neighborCount.get() == ) return new Empty(row, column); // starved else return new Fox(row, column, age + 1); public String tostring(){ return "Fox age " + age; char tochar() { return F ; Count getcount() { return neighborcount; static Count neighborcount = new Count(); private int age; private final int LIFE_EXPECTANCY = 5; 35 36 6

Why must getcount() and neighborcount be repeated in each subclass of Living? Why not just move these definitions to Living? Answer: There is no way to write a method in Living, that accesses a static field in the subclasses of Living. We need a neighborcount for each of Fox, Rabbit, Grass, and Empty. class Rabbit extends Living { Rabbit(int r, int c, int a ) { row = r; column = c; age = a; Count getcount() { return neighborcount; Interfaces An interface in Java, is essentially an pure abstract class - all methods are abstract. An interface can contain only abstract methods, and constants. There are no instance variables. static Count neighborcount = new Count(); private int age; private final int LIFE_EXPECTANCY = 3; 37 38 Suppose that different life forms have different notions of a neighborhood. Then in our simulation we can t provide computeneighbors() that works for all. We might just go with an interface instead of an abstract class. interface Living { Living next(world world); char tochar(); void computeneighbors(world world); Count getcount(); class Fox implements Living { // omitted methods/instance variables that are the // same as the earlier Fox class. public void computeneighbors(world world) { // each class must now define this method // an interface doesn t contain data fields // so row and column must be declared here // we can now make these members private private int row, column; 39 4 Multiple Inheritance What happens if a student is also a staff member? Person Multiple Inheritance What happens if a student is also a staff member? Person Student Faculty Staff Faculty Staff 41 Student 42 7

implements vs extends Java does not allow you to extend multiple classes. This avoids some problems related to multiple inheritance (e.g. what happens if you inherit a method from two different parent classes?). Java does allow you to implement multiple interfaces. Interfaces are about subtyping and polymorphism, whereas, inheriting methods interface Person { void setage(int age); void setgender(char gender); void setname(string name); int getage(); char getgender(); String getname(); is about code reuse. 43 44 interface Student extends Person { void setcollege(string college); void setgpa(double gpa); void setyear(byte year); String getcollege(); double getgpa(); byte getyear(); static final byte FROSH = 1; static final byte SOPH = 2; static final byte JUNIOR = 3; static final byte SENIOR = 4; import java.util.date; interface Staff extends Person { void setsalary(double salary); void setstartdate(date start); void setenddate(date end); void setssn(string ssn); double getsalary(); Date getstartdate(); Date getenddate(); String getssn(); 45 46 import java.util.date; class StudentEmployee implements Student, Staff { // methods required by Person public void setage(int age){ public String getname(){ // methods required by Student public void setcollege(string college){ public byte getyear(){ // methods required by Staff public void setsalary(double salary){ public String getssn(){ 47 Can t instantiate an interface Just as with abstract classes, you can declare variables and parameters to be of an interface type, but you cannot create objects of an interface type. Using the declartions on the previous slides, new Staff() would be illegal. You could declare a variable or parameter to be of type Staff. This variable would always either be null or refer to an instance of some class that implements the interface 48 Staff. 8

instanceof if (x intanceof Shape) // x is a Shape, act accordingly else // x is not a Shape, act accordingly Person person = new Student(); if (person instanceof Student) { Student student = (Student)person; // operate on student 49 Illegal Cast Some illegal casts can be determined at compile time, others can only be detected at runtime. Trying to cast a Person into a String is a compile time error. The compiler knows that String is not a subclass of Person and hence the cast is always illegal. Trying to cast a Person into a Student, when the Person is not a Student, is a runtime error - even if YOU can see that this person couldn't possibly be a Student. 5 ClassCastException The following can only be detected at runtime, even though you can see it is clearly illegal. Person person = new Person(); Student student = (Student)person; // GenericArray.java - // demonstrate generic array container class GenericArray { Object[] array = new Object[4]; array[] = "String 1"; array[1] = new Integer(1); array[2] = "String 2"; array[3] = new Integer(2); for (int i = ; i < array.length; i++) { // see next slide for the body of the loop // end of for loop 51 52 if (array[i] instanceof String) { String temp = (String)array[i]; System.out.println("Processing string " + temp); // do something appropriate for strings else if (array[i] instanceof Integer) { Integer temp = (Integer)array[i]; System.out.println("Processing Integer " + temp); // do something appropriate for an Integer else { System.out.println("Unexpected type " + array[i]); // do something to handle unexpected cases 53 9