Announcements. Final exam. Course evaluations. Saturday Dec 15 10:20 am -- 12:20 pm Room: TBA

Similar documents
Chapter 13. Inheritance and Polymorphism. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

Week 11. Abstract Data Types. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

Inheritance and Polymorphism

Chapter 10. Further Abstraction Techniques

Chapter 4. Inheritance

CS-202 Introduction to Object Oriented Programming

Polymorphism. Chapter 4. CSC 113 King Saud University College of Computer and Information Sciences Department of Computer Science. Dr. S.

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

CISC-124. Passing Parameters. A Java method cannot change the value of any of the arguments passed to its parameters.

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University

What is Inheritance?

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

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

Java Object Oriented Design. CSC207 Fall 2014

1 Shyam sir JAVA Notes

OOPs Concepts. 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8.

Inheritance (continued) Inheritance

ECE 122. Engineering Problem Solving with Java

Inheritance, Polymorphism, and Interfaces

Day 3. COMP 1006/1406A Summer M. Jason Hinek Carleton University

User Defined Classes Part 2. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

Chapter 5. Inheritance

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II

CREATED BY: Muhammad Bilal Arslan Ahmad Shaad. JAVA Chapter No 5. Instructor: Muhammad Naveed

Inheritance (Outsource: )

Practice for Chapter 11

CS260 Intro to Java & Android 03.Java Language Basics

Polymorphism. Final Exam. November 26, Method Overloading. Quick Review of Last Lecture. Overriding Methods.

Super-Classes and sub-classes

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

Programming Language Concepts Object-Oriented Programming. Janyl Jumadinova 28 February, 2017

More Relationships Between Classes

CS 180 Final Exam Review 12/(11, 12)/08

CS 251 Intermediate Programming Inheritance

Chapter 5 Object-Oriented Programming

25. Generic Programming

Implements vs. Extends When Defining a Class

Inheritance -- Introduction

Abstract Classes and Interfaces

Inheritance and Polymorphism

Class, Variable, Constructor, Object, Method Questions

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

Inheritance and object compatibility

Distributed Systems Recitation 1. Tamim Jabban

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

Chapter 11 Inheritance and Polymorphism. Motivations. Suppose you will define classes to model circles,

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

Programming in C# Inheritance and Polymorphism

CMSC 132: Object-Oriented Programming II. Inheritance

Distributed Systems Recitation 1. Tamim Jabban

Lecture 4: Extending Classes. Concept

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Programming II (CS300)

JAVA MOCK TEST JAVA MOCK TEST II

CS Programming I: Inheritance

8. Polymorphism and Inheritance

Lecture 36: Cloning. Last time: Today: 1. Object 2. Polymorphism and abstract methods 3. Upcasting / downcasting

Exercise: Singleton 1

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Announcements. Final exam. Course evaluations. No classes next week. Saturday Dec 15 10:20 am -- 12:20 pm Room: TBA. Wednesday November 28th

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.

Polymorphism and Inheritance

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

Java Magistère BFA

Starting Out with Java: From Control Structures Through Objects Sixth Edition

CS/B.TECH/CSE(New)/SEM-5/CS-504D/ OBJECT ORIENTED PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70 GROUP A. (Multiple Choice Type Question)

More On inheritance. What you can do in subclass regarding methods:

Islamic University of Gaza Faculty of Engineering Computer Engineering Department

Arrays Classes & Methods, Inheritance

VIRTUAL FUNCTIONS Chapter 10

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Rules and syntax for inheritance. The boring stuff

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

Inheritance and Interfaces

Informatik II (D-ITET) Tutorial 6

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber

User Defined Classes. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

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

Introduction to Programming Using Java (98-388)

CSCI-142 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community

First IS-A Relationship: Inheritance

CSC207H: Software Design. Java + OOP. CSC207 Winter 2018

A base class (superclass or parent class) defines some generic behavior. A derived class (subclass or child class) can extend the base class.

Informatik II. Tutorial 6. Mihai Bâce Mihai Bâce. April 5,

Java Fundamentals (II)

HAS-A Relationship. If A uses B, then it is an aggregation, stating that B exists independently from A.

Programming Exercise 14: Inheritance and Polymorphism

Lecture 10. Overriding & Casting About

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

CMSC131. Inheritance. Object. When we talked about Object, I mentioned that all Java classes are "built" on top of that.

Lecture Notes Chapter #9_b Inheritance & Polymorphism

CS 112 Programming 2. Lecture 06. Inheritance & Polymorphism (1) Chapter 11 Inheritance and Polymorphism

CSC207H: Software Design. Java + OOP. CSC207 Winter 2018

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

Inheritance (Part 5) Odds and ends

Inheritance & Abstract Classes Fall 2018 Margaret Reid-Miller

ITI Introduction to Computing II

Inheritance and Polymorphism

Comp 249 Programming Methodology

Transcription:

Announcements Final exam Saturday Dec 15 10:20 am -- 12:20 pm Room: TBA Course evaluations Wednesday November 28th Need volunteer to collect evaluations and deliver them to LWSN. 1

Chapter 13 Inheritance and Polymorphism CS 180 Sunil Prabhakar Department of Computer Science Purdue University

Introduction Inheritance and polymorphism are key concepts of Object Oriented Programming. Inheritance facilitates the reuse of code. A subclass inherits members (data and methods) from all its ancestor classes. The subclass can add more functionality to the class or replace some functionality that it inherits. Polymorphism simplifies code by automatically using the appropriate method for a given object. Polymorphism also makes it easy to extend code. 3

Inheritance A superclass corresponds to a general class, and a subclass is a specialization of the superclass. E.g. Account, Checking, Savings. Behavior and data common to the subclasses is often available in the superclass. E.g. Account number, owner name, data opened. Each subclass provides behavior and data that is relevant only to the subclass. E.g. Minimum balance for checking a/c, interest rate and computation for savings account. The common behavior is implemented once in the superclass and automatically inherited by the subclasses. 4

Defining Classes with Inheritance Case Study: Suppose we want implement a class roster that contains both undergraduate and graduate students. Each student s record will contain his or her name, three test scores, and the final course grade. The formula for determining the course grade is different for graduate students than for undergraduate students. 5

Modeling Two Types of Students There are two ways to design the classes to model undergraduate and graduate students. We can define two unrelated classes, one for undergraduates and one for graduates. We can model the two kinds of students by using classes that are related in an inheritance hierarchy. Two classes are unrelated if they are not connected in an inheritance relationship. NOTE: all classes inherit from Object 6

Classes for the Class Roster For the Class Roster sample, we design three classes: Student UndergraduateStudent GraduateStudent The Student class will incorporate behavior and data common to both UndergraduateStudent and GraduateStudent objects. The UndergraduateStudent class and the GraduateStudent class will each contain behaviors and data specific to their respective objects. 7

Creating a subclass We use the keyword extends in the class header to declare that it is a subclass: public class GraduateStudent extends Student { Student is the superclass, parent, or base class. A parent (of a parent ) is an ancestor class. GraduateStudent is the subclass, child, or derived class. A child (of a child...) is a descendent class. If a class does have the extend keyword, then it derives from the Object class. 8

Example: Student class Student { protected final static int NUM_OF_TESTS = 3; protected String name; protected int[] test; protected String coursegrade; public Student( ) { this("no Name"); public Student(String studentname) { name = studentname; test = new int[num_of_tests]; coursegrade = "****"; public String getcoursegrade( ) { return coursegrade; public String getname( ) { return name; public int gettestscore(int testnumber) { return test[testnumber-1]; public void setname(string newname) { name = newname; public void settestscore(int testnumber, int testscore) { test[testnumber-1] = testscore; public void computecoursegrade(); 9

Example: GraduateStudent class GraduateStudent extends Student{ public void computecoursegrade() { int total = 0; for (int i = 0; i < NUM_OF_TESTS; i++) { total += test[i]; if (total / NUM_OF_TESTS >= 80) { coursegrade = "Pass"; else { coursegrade = "No Pass"; 10

Example: UndergraduateStudent class UndergraduateStudent extends Student{ public void computecoursegrade() { int total = 0; for (int i = 0; i < NUM_OF_TESTS; i++) { total += test[i]; if (total / NUM_OF_TESTS >= 70) { coursegrade = "Pass"; else { coursegrade = "No Pass"; 11

Inheritance Hierarchy Student New visibility modifier: # protected + NUM_OF_TESTS # name # test # coursegrade + Student(): void + Student(String): void + getcoursegrade(): String + getname(): String + gettestscore(int): int + setname(string): void + settestscore(int, int): void UndergraduateStudent GraduateStudent + computecoursegrade(): void + computecoursegrade(): void 12

Overriding All non-private members of a class are inherited by derived classes This includes instance and class members A derived class may however, override an inherited method Data members can also be overridden but should be avoided since it only creates confusion. To override a method, the derived class simply defines a method with the same name, number and types of parameters (same signature) An overridden method cannot change the return type! A subclass may overload any method (inherited or otherwise) by using the same name, but different signature. 13

Overriding and overloading Sup sup = new Sup(); Sub sub = new Sub(); int i=9; char c = 'c'; sup.methoda(); sup.methoda(i); sub.methoda(); Sup methoda(int i){ Sub methoda(char c){ sub.methoda(i); sub.methoda(c); sup.methoda(c); 14

Overriding and overloading Sup sup = new Sup(); Sub sub = new Sub(); int i=9; char c = 'c'; sup.methoda(); sup.methoda(i); sub.methoda(); Sup methoda(int i){ Sub methoda(char c){ sub.methoda(i); sub.methoda(c); sup.methoda(c); 14

Overriding and overloading Sup sup = new Sup(); Sub sub = new Sub(); int i=9; char c = 'c'; sup.methoda(); sup.methoda(i); sub.methoda(); Sup methoda(int i){ Sub methoda(char c){ sub.methoda(i); sub.methoda(c); sup.methoda(c); 14

Overriding and overloading Sup sup = new Sup(); Sub sub = new Sub(); int i=9; char c = 'c'; sup.methoda(); sup.methoda(i); sub.methoda(); Sup methoda(int i){ Sub methoda(char c){ sub.methoda(i); sub.methoda(c); sup.methoda(c); 14

Overriding and overloading Sup sup = new Sup(); Sub sub = new Sub(); int i=9; char c = 'c'; sup.methoda(); sup.methoda(i); sub.methoda(); Sup methoda(int i){ Sub methoda(char c){ sub.methoda(i); sub.methoda(c); sup.methoda(c); 14

Overriding and overloading Sup sup = new Sup(); Sub sub = new Sub(); int i=9; char c = 'c'; sup.methoda(); sup.methoda(i); sub.methoda(); sub.methoda(i); sub.methoda(c); sup.methoda(c); overloaded Sup methoda(int i){ Sub methoda(char c){ 14

Overriding and overloading Sup sup = new Sup(); Sub sub = new Sub(); int i=9; char c = 'c'; sup.methoda(); sup.methoda(i); sub.methoda(); Sup methoda(int i){ Sub methoda(char c){ sub.methoda(i); sub.methoda(c); sup.methoda(c); 14

Overriding and overloading Sup sup = new Sup(); Sub sub = new Sub(); int i=9; char c = 'c'; sup.methoda(); sup.methoda(i); sub.methoda(); Sup methoda(int i){ Sub methoda(char c){ sub.methoda(i); sub.methoda(c); sup.methoda(c); 14

Overriding and overloading Sup sup = new Sup(); Sub sub = new Sub(); int i=9; char c = 'c'; Sup methoda(int i){ sup.methoda(); sup.methoda(i); sub.methoda(); sub.methoda(i); sub.methoda(c); sup.methoda(c); overridden Sub methoda(char c){ 14

Overriding and overloading Sup sup = new Sup(); Sub sub = new Sub(); int i=9; char c = 'c'; sup.methoda(); sup.methoda(i); sub.methoda(); Sup methoda(int i){ Sub methoda(char c){ sub.methoda(i); sub.methoda(c); sup.methoda(c); 14

Overriding and overloading Sup sup = new Sup(); Sub sub = new Sub(); int i=9; char c = 'c'; sup.methoda(); sup.methoda(i); sub.methoda(); Sup methoda(int i){ Sub methoda(char c){ sub.methoda(i); sub.methoda(c); sup.methoda(c); 14

Overriding and overloading Sup sup = new Sup(); Sub sub = new Sub(); int i=9; char c = 'c'; sup.methoda(); sup.methoda(i); sub.methoda(); sub.methoda(i); sub.methoda(c); sup.methoda(c); inherited Sup methoda(int i){ Sub methoda(char c){ 14

Overriding and overloading Sup sup = new Sup(); Sub sub = new Sub(); int i=9; char c = 'c'; sup.methoda(); sup.methoda(i); sub.methoda(); Sup methoda(int i){ Sub methoda(char c){ sub.methoda(i); sub.methoda(c); sup.methoda(c); 14

Overriding and overloading Sup sup = new Sup(); Sub sub = new Sub(); int i=9; char c = 'c'; sup.methoda(); sup.methoda(i); sub.methoda(); Sup methoda(int i){ Sub methoda(char c){ sub.methoda(i); sub.methoda(c); sup.methoda(c); 14

Overriding and overloading Sup sup = new Sup(); Sub sub = new Sub(); int i=9; char c = 'c'; Sup methoda(int i){ sup.methoda(); sup.methoda(i); sub.methoda(); sub.methoda(i); sub.methoda(c); sup.methoda(c); overridden & overloaded Sub methoda(char c){ 14

Overriding and overloading Sup sup = new Sup(); Sub sub = new Sub(); int i=9; char c = 'c'; sup.methoda(); sup.methoda(i); sub.methoda(); Sup methoda(int i){ Sub methoda(char c){ sub.methoda(i); sub.methoda(c); sup.methoda(c); 14

Overriding and overloading Sup sup = new Sup(); Sub sub = new Sub(); int i=9; char c = 'c'; sup.methoda(); sup.methoda(i); sub.methoda(); Sup methoda(int i){ Sub methoda(char c){ sub.methoda(i); sub.methoda(c); sup.methoda(c); 14

Overriding and overloading Sup sup = new Sup(); Sub sub = new Sub(); int i=9; char c = 'c'; sup.methoda(); sup.methoda(i); sub.methoda(); Sup methoda(int i){ Overloaded & Auto cast Sub methoda(char c){ sub.methoda(i); sub.methoda(c); sup.methoda(c); 14

Overriding and overloading Sup sup = new Sup(); Sub sub = new Sub(); int i=9; char c = 'c'; sup.methoda(); sup.methoda(i); sub.methoda(); Sup methoda(int i){ Sub methoda(char c){ sub.methoda(i); sub.methoda(c); sup.methoda(c); 14

Limiting inheritance and overriding If a class is declared to be final, then no other classes can derive from it. public final class ClassA If a method is declared to be final, then no derived class can override this method. A final method can be overloaded in a derived class though. public final void methoda() 15

The protected Modifier The modifier protected makes a data member or method visible and accessible only to instances of the class and descendant classes. public data members and methods are accessible to everyone. private data members and methods are accessible only to instances of the class. protected is similar to: public for descendant classes private for any other class 16

Inheritance and Member Accessibility We use the following visual representation of inheritance to illustrate data member accessibility. public protected private Accessible Inaccessible 17

Inheritance and Member Accessibility We use the following visual representation of inheritance to illustrate data member accessibility. public protected private Super Accessible Inaccessible Sub Class Hierarchy 17

Inheritance and Member Accessibility We use the following visual representation of inheritance to illustrate data member accessibility. public protected private Super :Super Instances Accessible Inaccessible Sub :Sub :Super This shows the inherited components of the superclass are part of the subclass instance Class Hierarchy 17

The Effect of the Visibility Modifiers public protected private :Super Accessible Inaccessible :Client :Sub :Super Accessibility from a Client method 18

The Effect of the Visibility Modifiers public protected private :Super Accessible Inaccessible :Client :Sub :Super Accessibility from a Client method Only public members, those defined for the class and those inherited, are visible from outside. All else is hidden from the outside. 18

The Effect of the Visibility Modifiers public protected private :Super Accessible Inaccessible :Client :Sub :Super Accessibility from a Client method Only public members, those defined for the class and those inherited, are visible from outside. All else is hidden from the outside. 18

The Effect of the Visibility Modifiers public protected private :Super Accessible Inaccessible :Client Accessibility from a Client method :Sub :Super Only public members, those defined for the class and those inherited, are visible from outside. All else is hidden from the outside. 18

The Effect of the Visibility Modifiers public protected private :Super Accessible Inaccessible :Client Accessibility from a Client method Only public members, those defined for the class and those inherited, are visible from outside. All else is hidden from the outside. :Sub :Super 18

The Effect of the Visibility Modifiers public protected private :Client :Super Accessible Inaccessible Accessibility from a Client method Only public members, those defined for the class and those inherited, are visible from outside. All else is hidden from the outside. :Sub :Super 18

Accessibility of Super from Sub public protected private Accessibility from a method of the Sub class :Super :Sub 19

Accessibility of Super from Sub public protected private Accessibility from a method of the Sub class :Super :Sub From a method of the Sub, everything is visible except the private members of its super class. 19

Accessibility of Super from Sub public protected private Accessibility from a method of the Sub class :Super :Sub From a method of the Sub, everything is visible except the private members of its super class. 19

Accessibility of Super from Sub public protected private Accessibility from a method of the Sub class From a method of the Sub, everything is visible except the private members of its super class. :Super :Sub 19

Accessibility from Another Instance Data members accessible from an instance are also accessible from other instances of the same class. one:classa two:classa This could be private, Protected, or public. 20

Inheritance and Constructors Unlike members of a superclass, constructors of a superclass are not inherited by its subclasses. As always, each class that does not define a constructor is automatically given a default constructor. In addition, in each constructor of a derived class, we must make a call to the constructor of the base class by calling: super(); This must be the first statement in the constructor. If this statement is not present, the compiler automatically adds it as the first statement. You may optionally call some other constructor of the base class, e.g.: super( some string ); 21

Constructors and inheritance The constructor for each class can be used to initialize the variables defined in that class. For all classes, calls to the constructors are chained all the way back to the constructor for the Object class. Recall that it is also possible to call another constructor of the same class using the this keyword. However, this must also be the first statement of the constructor! A constructor cannot call another constructor of the same class and the base class. 22

Constructors Sup public Sup(){ public Sup(int i){ Sub public Sub(){ this( x ); public Sub(char c){ public Sub(int i){ super(i); 23

Constructors Sup public Sup(){ public Sup(int i){ Sup public Sup(){ super(); public Sup(int i){ super(); Sub public Sub(){ this( x ); public Sub(char c){ public Sub(int i){ super(i); Sub public Sub(){ this( x ); public Sub(char c){ super(); public Sub(int i){ super(i); Added by the compiler 23

Constructors Sup public Sup(){ public Sup(int i){ Sub public Sub(){ this( x ); public Sub(char c){ public Sub(int i){ super(i); Sup sup1, sup2; Sub sub1, sub2, sub3; sup1 = new Sup(); sup2 = new Sup(7); sub1 = new Sub(); sub2 = new Sub( y ); sub3 = new Sub(5); Sup public Sup(){ super(); public Sup(int i){ super(); Sub public Sub(){ this( x ); public Sub(char c){ super(); public Sub(int i){ super(i); Added by the compiler 23

Super keyword The super keyword is a call to the constructor of the parent class. It can also be used to call a method of the parent class: super.methoda(); This can be useful to call an overridden method. Similarly, it can be used to access data members of the parent. 24

super keyword example. Sup methoda(int i){ Sub methodb(){ methoda(); this.methoda(); super.methoda(); methoda(7); methoda( x ); 25

super keyword example. Sup methoda(int i){ Sub methodb(){ methoda(); this.methoda(); super.methoda(); methoda(7); methoda( x ); 25

super keyword example. Sup methoda(int i){ Sub methodb(){ methoda(); this.methoda(); super.methoda(); methoda(7); methoda( x ); 25

super keyword example. Sup methoda(int i){ Sub methodb(){ methoda(); this.methoda(); super.methoda(); methoda(7); methoda( x ); 25

super keyword example. Sup methoda(int i){ Sub methodb(){ methoda(); this.methoda(); super.methoda(); methoda(7); methoda( x ); 25

super keyword example. Sup methoda(int i){ Sub methodb(){ methoda(); this.methoda(); super.methoda(); methoda(7); methoda( x ); 25

Quiz Which method is executed for each of these calls? Sup sup = new Sup(); Sub sub = new Sub(); int i=9; char c='c'; String s= test sub.methoda(); sub.methoda(i); sub.methoda(s); sup.methoda(c); Sup methoda(int i){ Sub methoda(string s){ methoda(int j){ 26

Polymorphism Polymorphism allows a single variable to refer to objects from different subclasses in the same inheritance hierarchy For example, if Cat and Dog are subclasses of Pet, then the following statements are valid: 27

Polymorphism Polymorphism allows a single variable to refer to objects from different subclasses in the same inheritance hierarchy For example, if Cat and Dog are subclasses of Pet, then the following statements are valid: Pet mypet; mypet = new Dog();... mypet = new Cat(); 27

Creating the roster Array We can maintain our class roster using an array, combining objects from the Student, UndergraduateStudent, and GraduateStudent classes. Student roster = new Student[40];... roster[0] = new GraduateStudent(); roster[1] = new UndergraduateStudent(); roster[2] = new UndergraduateStudent();... 28

State of the roster Array The roster array with elements referring to instances of GraduateStudent or UndergraduateStudent classes. 29

State of the roster Array The roster array with elements referring to instances of GraduateStudent or UndergraduateStudent classes. 29

Sample Polymorphic Message To compute the course grade using the roster array, we execute 30

Sample Polymorphic Message To compute the course grade using the roster array, we execute for (int i = 0; i < numberofstudents; i++) { roster[i].computecoursegrade(); If roster[i] refers to a GraduateStudent, then the computecoursegrade method of the GraduateStudent class is executed. If roster[i] refers to an UndergraduateStudent, then the computecoursegrade method of the UndergraduateStudent class is executed. 30

Dynamic Binding At compile time, it is not known which version of a polymorphic method will get executed This is determined at run-time depending upon the class of the object This is called dynamic (late) binding Each object of a subclass is also an object of the superclass. But not vice versa! Do not confuse dynamic binding with overloaded methods. 31

Object Type Consider the inheritance hierarchy: Object A B An object of class B is also an object of classes A and Object. Thus we can use objects of class B wherever we can use objects of class A. The reverse is not true. A reference of type A can refer to an object of type B. However if we want to access the functionality of B on that object, we have to type cast to type B before doing that. 32

Polymorphism example Sup Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodB(); Sub sub1 = (Sub)sup; sub1.methoda(); Sub methodb(){ sub1.methodb(); 33

Polymorphism example Sup Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodB(); Sub sub1 = (Sub)sup; sub1.methoda(); Sub methodb(){ sub1.methodb(); 33

Polymorphism example Sup Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodB(); Sub sub1 = (Sub)sup; sub1.methoda(); Sub methodb(){ sub1.methodb(); sub 33

Polymorphism example Sup Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodB(); Sub sub1 = (Sub)sup; sub1.methoda(); Sub methodb(){ sub1.methodb(); sub :Sub 33

Polymorphism example Sup Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodB(); Sub sub1 = (Sub)sup; sub1.methoda(); Sub methodb(){ sub1.methodb(); sub :Sub 33

Polymorphism example Sup Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodB(); Sub sub1 = (Sub)sup; sub1.methoda(); Sub methodb(){ sub1.methodb(); sub :Sub 33

Polymorphism example Sup Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodB(); Sub sub1 = (Sub)sup; sub1.methoda(); Sub methodb(){ sub1.methodb(); sub :Sub 33

Polymorphism example Sup Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodB(); Sub sub1 = (Sub)sup; sub1.methoda(); Sub methodb(){ sub1.methodb(); sub sup :Sub 33

Polymorphism example Sup Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodB(); Sub sub1 = (Sub)sup; sub1.methoda(); Sub methodb(){ sub1.methodb(); sub sup :Sub 33

Polymorphism example Sup Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodB(); Sub sub1 = (Sub)sup; sub1.methoda(); Sub methodb(){ sub1.methodb(); sub sup :Sub 33

Polymorphism example Sup Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodB(); Sub sub1 = (Sub)sup; sub1.methoda(); Sub methodb(){ sub1.methodb(); sub sup :Sub 33

Polymorphism example Sup Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodB(); Sub sub1 = (Sub)sup; sub1.methoda(); Sub methodb(){ sub1.methodb(); sub sup :Sub 33

Polymorphism example Sup Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodB(); Sub sub1 = (Sub)sup; sub1.methoda(); Sub methodb(){ sub1.methodb(); sub sup :Sub 33

Polymorphism example Sup Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodB(); Sub sub1 = (Sub)sup; sub1.methoda(); Sub methodb(){ sub1.methodb(); sub sup :Sub 33

Polymorphism example Sup Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodB(); Sub sub1 = (Sub)sup; sub1.methoda(); Sub methodb(){ sub1.methodb(); sub sup :Sub 33

Polymorphism example Sup Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodB(); Sub sub1 = (Sub)sup; sub1.methoda(); Sub methodb(){ sub1.methodb(); sub sup :Sub 33

Polymorphism example Sup Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodB(); Sub sub1 = (Sub)sup; sub1.methoda(); Sub methodb(){ sub1.methodb(); sub sup :Sub 33

Polymorphism example Sup Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodB(); Sub sub1 = (Sub)sup; sub1.methoda(); sub1.methodb(); Sub methodb(){ Note: sup.methodb( ) will not compile. sub sup :Sub 33

Polymorphism example Sup Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodB(); Sub sub1 = (Sub)sup; sub1.methoda(); sub1.methodb(); Sub methodb(){ Note: sup.methodb( ) will not compile. sub sup :Sub 33

Polymorphism example Sup Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodB(); Sub sub1 = (Sub)sup; sub1.methoda(); sub1.methodb(); Sub methodb(){ Note: sup.methodb( ) will not compile. sub sup :Sub 33

Polymorphism example Sup Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodB(); Sub sub1 = (Sub)sup; sub1.methoda(); Sub methodb(){ Note: sup.methodb( ) will not compile. sub1.methodb(); sub sup sub1 :Sub 33

Polymorphism example Sup Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodB(); Sub sub1 = (Sub)sup; sub1.methoda(); Sub methodb(){ Note: sup.methodb( ) will not compile. sub1.methodb(); sub sup sub1 :Sub 33

Polymorphism example Sup Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodB(); Sub sub1 = (Sub)sup; sub1.methoda(); sub1.methodb(); sub sup sub1 Sub methodb(){ Note: sup.methodb( ) will not compile. Casting to Sub will work, but a runtime exception (ClassCastException) will be thrown if the object is not really a Sub object. :Sub 33

Polymorphism example Sup Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodB(); Sub sub1 = (Sub)sup; sub1.methoda(); sub1.methodb(); sub sup sub1 Sub methodb(){ Note: sup.methodb( ) will not compile. Casting to Sub will work, but a runtime exception (ClassCastException) will be thrown if the object is not really a Sub object. :Sub 33

Polymorphism example Sup Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodB(); Sub sub1 = (Sub)sup; sub1.methoda(); sub1.methodb(); sub sup sub1 Sub methodb(){ Note: sup.methodb( ) will not compile. Casting to Sub will work, but a runtime exception (ClassCastException) will be thrown if the object is not really a Sub object. :Sub 33

Polymorphism example Sup Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodB(); Sub sub1 = (Sub)sup; sub1.methoda(); sub1.methodb(); sub sup sub1 Sub methodb(){ Note: sup.methodb( ) will not compile. Casting to Sub will work, but a runtime exception (ClassCastException) will be thrown if the object is not really a Sub object. :Sub 33

Polymorphism example Sup Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodB(); Sub sub1 = (Sub)sup; sub1.methoda(); sub1.methodb(); sub sup sub1 Sub methodb(){ Note: sup.methodb( ) will not compile. Casting to Sub will work, but a runtime exception (ClassCastException) will be thrown if the object is not really a Sub object. :Sub 33

Polymorphism example Sup Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodB(); Sub sub1 = (Sub)sup; sub1.methoda(); sub1.methodb(); sub sup sub1 Sub methodb(){ Note: sup.methodb( ) will not compile. Casting to Sub will work, but a runtime exception (ClassCastException) will be thrown if the object is not really a Sub object. :Sub 33

Polymorphism example Sup Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodB(); Sub sub1 = (Sub)sup; sub1.methoda(); sub1.methodb(); sub sup sub1 Sub methodb(){ Note: sup.methodb( ) will not compile. Casting to Sub will work, but a runtime exception (ClassCastException) will be thrown if the object is not really a Sub object. :Sub 33

Polymorphism example Sup Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodB(); Sub sub1 = (Sub)sup; sub1.methoda(); sub1.methodb(); sub sup sub1 Sub methodb(){ Note: sup.methodb( ) will not compile. Casting to Sub will work, but a runtime exception (ClassCastException) will be thrown if the object is not really a Sub object. :Sub 33

Example Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodA(); sub = (Sub)sup; sub.methoda(); Sup methoda(string[] s){ Sub methoda(int i){ sub.methoda( test ); 34

Example Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodA(); sub = (Sub)sup; sub.methoda(); Sup methoda(string[] s){ Sub methoda(int i){ sub.methoda( test ); 34

Example Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodA(); sub = (Sub)sup; sub.methoda(); Sup methoda(string[] s){ Sub methoda(int i){ sub.methoda( test ); 34

Example Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodA(); sub = (Sub)sup; sub.methoda(); Sup methoda(string[] s){ Sub methoda(int i){ sub.methoda( test ); 34

Example Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodA(); sub = (Sub)sup; sub.methoda(); Sup methoda(string[] s){ Sub methoda(int i){ sub.methoda( test ); 34

Example Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodA(); sub = (Sub)sup; sub.methoda(); Sup methoda(string[] s){ Sub methoda(int i){ sub.methoda( test ); 34

Example Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodA(); sub = (Sub)sup; sub.methoda(); Sup methoda(string[] s){ Sub methoda(int i){ sub.methoda( test ); 34

Example Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodA(); sub = (Sub)sup; sub.methoda(); Sup methoda(string[] s){ Sub methoda(int i){ sub.methoda( test ); 34

Example Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodA(); sub = (Sub)sup; sub.methoda(); Sup methoda(string[] s){ Sub methoda(int i){ sub.methoda( test ); 34

Example Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodA(); sub = (Sub)sup; sub.methoda(); Sup methoda(string[] s){ Sub methoda(int i){ sub.methoda( test ); 34

Example Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodA(); sub = (Sub)sup; sub.methoda(); Sup methoda(string[] s){ Sub methoda(int i){ sub.methoda( test ); 34

Example Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodA(); sub = (Sub)sup; sub.methoda(); Sup methoda(string[] s){ Sub methoda(int i){ sub.methoda( test ); 34

Example Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodA(); sub = (Sub)sup; sub.methoda(); Sup methoda(string[] s){ Sub methoda(int i){ sub.methoda( test ); 34

The instanceof Operator The instanceof operator can help us discover the class of an object at runtime. The following code counts the number of undergraduate students. new undergradcount = 0; for (int i = 0; i < numberofstudents; i++) { if ( roster[i] instanceof UndergraduateStudent ) { undergradcount++; 35

Abstract Superclasses and Methods When we define a superclass, we often do not need to create any instances of the superclass. Depending on whether we need to create instances of the superclass, we must define the class differently. We will study examples based on the Student superclass defined earlier. 36

Definition: Abstract Class An abstract class is a class defined with the modifier abstract OR that contains an abstract method OR that does not provide an implementation of an inherited abstract method An abstract method is a method with the keyword abstract, and it ends with a semicolon instead of a method body. Private methods and static methods may not be declared abstract. No instances can be created from an abstract class. 37

Case 1 A Student must be Undergraduate or Graduate If a student must be either an undergraduate or a graduate student, we only need instances of UndergraduateStudent or GraduateStudent. Therefore, we should define the Student class so that no instances may be created of it. 38

Example: Abstract classes abstract class Student { protected final static int NUM_OF_TESTS = 3; protected String name; protected int[] test; protected String coursegrade; public Student( ) { this("no Name"); public Student(String studentname) { name = studentname; test = new int[num_of_tests]; coursegrade = "****"; public String getcoursegrade( ) { return coursegrade; public String getname( ) { return name; public int gettestscore(int testnumber) { return test[testnumber-1]; public void setname(string newname) { name = newname; public void settestscore(int testnumber, int testscore) { test[testnumber-1] = testscore; 39

Example: Abstract classes abstract class Student { protected final static int NUM_OF_TESTS = 3; protected String name; protected int[] test; protected String coursegrade; public Student( ) { this("no Name"); public Student(String studentname) { name = studentname; test = new int[num_of_tests]; coursegrade = "****"; public String getcoursegrade( ) { return coursegrade; public String getname( ) { return name; public int gettestscore(int testnumber) { return test[testnumber-1]; public void setname(string newname) { name = newname; public void settestscore(int testnumber, int testscore) { test[testnumber-1] = testscore; class UndergraduateStudent extends Student { public void computecoursegrade() { int total = 0; for (int i = 0; i < NUM_OF_TESTS; i++) { total += test[i]; if (total / NUM_OF_TESTS >= 70) { coursegrade = "Pass"; else { coursegrade = "No Pass"; 39

Example: Abstract classes abstract class Student { protected final static int NUM_OF_TESTS = 3; protected String name; protected int[] test; protected String coursegrade; public Student( ) { this("no Name"); public Student(String studentname) { name = studentname; test = new int[num_of_tests]; coursegrade = "****"; public String getcoursegrade( ) { return coursegrade; public String getname( ) { return name; public int gettestscore(int testnumber) { return test[testnumber-1]; public void setname(string newname) { name = newname; public void settestscore(int testnumber, int testscore) { test[testnumber-1] = testscore; class UndergraduateStudent extends Student { public void computecoursegrade() { int total = 0; for (int i = 0; i < NUM_OF_TESTS; i++) { total += test[i]; if (total / NUM_OF_TESTS >= 70) { coursegrade = "Pass"; else { coursegrade = "No Pass"; class GraduateStudent extends Student { public void computecoursegrade() { int total = 0; for (int i = 0; i < NUM_OF_TESTS; i++) { total += test[i]; if (total / NUM_OF_TESTS >= 80) { coursegrade = "Pass"; else { coursegrade = "No Pass"; 39

Abstract example (contd.) Non-private members of the abstract parent class are inherited. Note: constructors are not inherited! Default constructor calls super! public class Test { public static void main(string[ ] args){ Student s; GraduateStudent g; UndergraduateStudent u; s = new Student(); g = new GraduateStudent( John ); g = new GraduateStudent(); u = new UndergraduateStudent(); System.out.println(g.getName()); System.out.println(u.getName()); 40

Abstract example (contd.) Non-private members of the abstract parent class are inherited. Note: constructors are not inherited! Default constructor calls super! public class Test { public static void main(string[ ] args){ Student s; GraduateStudent g; UndergraduateStudent u; Cannot instantiate abstract class. s = new Student(); g = new GraduateStudent( John ); g = new GraduateStudent(); u = new UndergraduateStudent(); System.out.println(g.getName()); System.out.println(u.getName()); 40

Abstract example (contd.) Non-private members of the abstract parent class are inherited. Note: constructors are not inherited! Default constructor calls super! public class Test { public static void main(string[ ] args){ Student s; GraduateStudent g; UndergraduateStudent u; Cannot instantiate abstract class. s = new Student(); g = new GraduateStudent( John ); g = new GraduateStudent(); u = new UndergraduateStudent(); System.out.println(g.getName()); System.out.println(u.getName()); Error: constructor not inherited! 40

Abstract example (contd.) Non-private members of the abstract parent class are inherited. Note: constructors are not inherited! Default constructor calls super! public class Test { public static void main(string[ ] args){ Student s; GraduateStudent g; UndergraduateStudent u; Cannot instantiate abstract class. s = new Student(); g = new GraduateStudent( John ); g = new GraduateStudent(); u = new UndergraduateStudent(); System.out.println(g.getName()); System.out.println(u.getName()); Error: constructor not inherited! Inherited from abstract parent class. 40

Case 2 Student does not have to be Undergraduate or Graduate. In this case, we may design the Student class in one of two ways. We can make the Student class instantiable. We can leave the Student class abstract and add a third subclass, OtherStudent, to handle a student who does not fall into the UndergraduateStudent or GraduateStudent categories. 41

Which Approach to Use? The best approach depends on the particular situation. When considering design options, we can ask ourselves which approach allows easier modification and extension. 42

Inheritance versus Interface The Java interface is used to share common behavior (only method headers) among the instances of different classes. Inheritance is used to share common code (including both data members and methods) among the instances of related classes. In your program designs, remember to use the Java interface to share common behavior. Use inheritance to share common code. If an entity A is a specialized form of another entity B, then model them using inheritance. Declare A as a subclass of B. 43

Interface vs inheritance Interface Inheritance Data members? No Yes Methods? Only headers -- no body Yes Keyword implements extends Multiple? Yes No Instantiable? No Yes (if not abstract) An interface essentially provides compliance with some desired behavior. Inheritance allows sharing of code. 44

Interfaces A class does not extend an interface, instead it implements an interface. Implementing implies that the class must provide the bodies for all the methods specified in the interface i.e. with the same signatures & return types Remember: GUI interfaces ActionListener 45

Introduction to Data Structures A data structure is a specific organization of data for efficiency or ease of coding. E.g. an array allows us to manage a large number of similar items. Many different types of data structures are used in programming. CS251 deals only with this topic! We will look at two example data structures Linked list Queue 46

Linked List Recall that an array s capacity is fixed once it is created or initialized. The LinkedList class in java.util used a linked list to implement a variable size list of objects. How does this work? We will study it by creating our own version of the LinkedList class which can store a list of objects of any class, in order. 47

Objective The linked list will allow us to Create an empty list. Add items to the end of the list. Delete items from the end of the list. Iterate through the list from beginning to end. Note: no position indexing in this version. Our linked list will be implemented as a chain of Node objects. Each Node object will have An Object data member that is the value stored at that position. A reference to the next node in the list. 48

The Node Class class Node { private Node next; private Object content; public void Node() { next = null; content = null; public Object getcontent(){ return content; public void setcontent(object c){ content = c; public Node getnext(){ return next; public void setnext(node nextnode){ next = nextnode; :Node next content 49

The LinkedList class class LinkedList { private Node head; private Node iterator; public void LinkedList() { head = null; iterator = null; public void addtohead(object c){ Node n = new Node(); n.setcontent(c); n.setnext(head); head = n; public void deletefromhead throws Exception (){ if(head== null) throw new Exception( Empty List ); else head = head.getnext(); public void getfromhead throws Exception (){ if(head== null) throw new Exception( Empty List ); else return head.getcontent(); public void startscan throws Exception (){ if(head == null) throw new Exception( Empty List ); else iterator = head; public boolean hasmore(){ if(iterator.next == null) return false; else return true; public void moveahead(){ iterator = iterator.getnext(); public Object getcurrentitem throws Exception (){ if(iterator == null) throw new Exception( No Current Item ); return iterator.getcontent(); 50

Example LinkedList list; list = new LinkedList(); String s; s = test1 ; List.addToHead(s); s = test2 ; list.addtohead(s); s = test3 ; list.addtohead(s); 51

Example list LinkedList list; list = new LinkedList(); String s; s = test1 ; List.addToHead(s); s = test2 ; list.addtohead(s); s = test3 ; list.addtohead(s); 51

Example list :LinkedList head iterator LinkedList list; list = new LinkedList(); String s; s = test1 ; List.addToHead(s); s = test2 ; list.addtohead(s); s = test3 ; list.addtohead(s); 51

Example list :LinkedList head iterator LinkedList list; list = new LinkedList(); String s; s = test1 ; List.addToHead(s); s = test2 ; list.addtohead(s); s = test3 ; list.addtohead(s); s 51

Example list :LinkedList head iterator test1 LinkedList list; list = new LinkedList(); String s; s = test1 ; List.addToHead(s); s = test2 ; list.addtohead(s); s = test3 ; list.addtohead(s); s 51

Example list :LinkedList head iterator :Node content next test1 LinkedList list; list = new LinkedList(); String s; s = test1 ; List.addToHead(s); s = test2 ; list.addtohead(s); s = test3 ; list.addtohead(s); s 51

Example list :LinkedList head iterator :Node content next test1 LinkedList list; list = new LinkedList(); String s; s = test1 ; List.addToHead(s); s = test2 ; list.addtohead(s); s = test3 ; list.addtohead(s); s 51

Example list :LinkedList head iterator :Node content next test1 LinkedList list; list = new LinkedList(); String s; s = test1 ; List.addToHead(s); s = test2 ; list.addtohead(s); s = test3 ; list.addtohead(s); s 52

Example list :LinkedList head iterator :Node content next test1 LinkedList list; list = new LinkedList(); String s; s = test1 ; List.addToHead(s); s = test2 ; list.addtohead(s); s = test3 ; list.addtohead(s); test2 s 52

Example list :LinkedList head iterator :Node content next test1 LinkedList list; list = new LinkedList(); String s; s = test1 ; List.addToHead(s); s = test2 ; list.addtohead(s); s = test3 ; list.addtohead(s); test2 s 52

Example list :LinkedList head iterator :Node content next test1 LinkedList list; list = new LinkedList(); String s; s = test1 ; List.addToHead(s); s = test2 ; :Node content next test2 s list.addtohead(s); s = test3 ; list.addtohead(s); 52

Example list :LinkedList head iterator :Node content next test1 LinkedList list; list = new LinkedList(); String s; s = test1 ; List.addToHead(s); s = test2 ; :Node content next test2 s list.addtohead(s); s = test3 ; list.addtohead(s); 52

Example list :LinkedList head iterator :Node content next test1 LinkedList list; list = new LinkedList(); String s; s = test1 ; List.addToHead(s); s = test2 ; :Node content next test2 s list.addtohead(s); s = test3 ; list.addtohead(s); 53

Example list :LinkedList head iterator :Node content next test1 LinkedList list; list = new LinkedList(); String s; s = test1 ; List.addToHead(s); s = test2 ; :Node content next test2 s list.addtohead(s); s = test3 ; list.addtohead(s); test3 53

Example list :LinkedList head iterator :Node content next test1 LinkedList list; list = new LinkedList(); String s; s = test1 ; List.addToHead(s); s = test2 ; :Node content next test2 s list.addtohead(s); s = test3 ; list.addtohead(s); test3 53

Example list :LinkedList head iterator :Node content next test1 LinkedList list; list = new LinkedList(); String s; s = test1 ; List.addToHead(s); s = test2 ; :Node content next test2 s list.addtohead(s); s = test3 ; list.addtohead(s); :Node content test3 next 53

Example list :LinkedList head iterator :Node content next test1 LinkedList list; list = new LinkedList(); String s; s = test1 ; List.addToHead(s); s = test2 ; :Node content next test2 s list.addtohead(s); s = test3 ; list.addtohead(s); :Node content test3 next 53

Example list :LinkedList head iterator :Node content next test1 :Node list.startscan(); s = (String) list.getcurrentitem(); System.out.println(s); while(list.hasmore()){ list.moveahead(); s = (String) list.getcurrentitem(); System.out.println(s); content next :Node content next test2 test3 s 54

Example list :LinkedList head iterator :Node content next test1 :Node list.startscan(); s = (String) list.getcurrentitem(); System.out.println(s); while(list.hasmore()){ list.moveahead(); s = (String) list.getcurrentitem(); System.out.println(s); content next :Node content next test2 test3 s 54

Example list :LinkedList head iterator :Node content next test1 :Node list.startscan(); s = (String) list.getcurrentitem(); System.out.println(s); while(list.hasmore()){ list.moveahead(); s = (String) list.getcurrentitem(); System.out.println(s); content next :Node content next test2 test3 s 54

Example list :LinkedList head iterator :Node content next test1 :Node list.startscan(); s = (String) list.getcurrentitem(); System.out.println(s); while(list.hasmore()){ list.moveahead(); s = (String) list.getcurrentitem(); System.out.println(s); content next :Node content next test2 test3 s 54

Example list :LinkedList head iterator :Node content next test1 :Node list.startscan(); s = (String) list.getcurrentitem(); System.out.println(s); while(list.hasmore()){ list.moveahead(); s = (String) list.getcurrentitem(); System.out.println(s); content next :Node content next test2 test3 s 54

Example list :LinkedList head iterator :Node content next test1 :Node list.startscan(); s = (String) list.getcurrentitem(); System.out.println(s); while(list.hasmore()){ list.moveahead(); s = (String) list.getcurrentitem(); System.out.println(s); content next :Node content next test2 test3 s 54

Example list :LinkedList head iterator :Node content next test1 :Node list.startscan(); s = (String) list.getcurrentitem(); System.out.println(s); while(list.hasmore()){ list.moveahead(); s = (String) list.getcurrentitem(); System.out.println(s); content next :Node content next test2 test3 s 54

Example list :LinkedList head iterator :Node content next test1 :Node content next test2 list.deletefromhead(); :Node content next test3 55

Example list :LinkedList head iterator :Node content next test1 :Node content next test2 list.deletefromhead(); :Node content next test3 55

Example list :LinkedList head iterator :Node content next test1 :Node content next test2 list.deletefromhead(); test3 55

Example list :LinkedList head iterator :Node content next test1 :Node content next test2 list.deletefromhead(); 55

Queue A similar Node class can be used to implement another data structure called a First-In-First-out (FIFO) queue. A FIFO queue is often used by operating systems for processes, requests, etc. In a FIFO queue, items are added at one end and deleted from the other end. For this we need to have pointers going in both directions: Node2 56

The Node2 Class class Node2 { private Node2 next, prev; private Object content; public void Node2() { next = null; prev = null; content = null; public Object getcontent(){ return content; public void setcontent(object c){ content = c; public Node2 getnext(){ return next; public void setnext(node2 nextnode){ next = nextnode; public Node getprev(){ return prev; public void setprev(node2 prevnode){ prev = prevnode; :Node2 next content prev 57

The FifoQ class class FifoQ { private Node2 head, tail; public void FifoQ() { head = null; tail = null; public void addtoq(object c){ Node2 n = new Node2(); n.setcontent(c); n.setnext(head); head.setprev(n); head = n; public void deletefromq throws Exception (){ if(tail== null) throw new Exception( Empty Queue ); if(tail.getprev() == null){ tail = null; head = null; else { tail = tail.getprev(); tail.setnext(null); 58

Example FifoQ q; q = new FifoQ(); String s; s = test1 ; q.addtoq(s); s = test2 ; q.addtoq(s); while(!q.isempty()) q.deletefromq(); 59

Example q FifoQ q; q = new FifoQ(); String s; s = test1 ; q.addtoq(s); s = test2 ; q.addtoq(s); while(!q.isempty()) q.deletefromq(); 59

Example q :FifoQ FifoQ q; q = new FifoQ(); String s; s = test1 ; q.addtoq(s); s = test2 ; q.addtoq(s); while(!q.isempty()) q.deletefromq(); tail head 59

Example q :FifoQ FifoQ q; q = new FifoQ(); String s; s = test1 ; q.addtoq(s); s = test2 ; q.addtoq(s); while(!q.isempty()) q.deletefromq(); tail head test1 s 59

Example q FifoQ q; q = new FifoQ(); String s; s = test1 ; q.addtoq(s); s = test2 ; q.addtoq(s); while(!q.isempty()) q.deletefromq(); :FifoQ tail head :Node2 next content prev test1 s 59

Example q FifoQ q; q = new FifoQ(); String s; s = test1 ; q.addtoq(s); s = test2 ; q.addtoq(s); while(!q.isempty()) q.deletefromq(); :FifoQ tail head :Node2 next content prev test1 s 59

Example q FifoQ q; q = new FifoQ(); String s; s = test1 ; q.addtoq(s); s = test2 ; q.addtoq(s); while(!q.isempty()) q.deletefromq(); :FifoQ tail head :Node2 next content prev test1 s 59

Example q FifoQ q; q = new FifoQ(); String s; s = test1 ; q.addtoq(s); s = test2 ; q.addtoq(s); while(!q.isempty()) q.deletefromq(); :FifoQ tail head :Node2 next content prev test1 s 60

Example q FifoQ q; q = new FifoQ(); String s; s = test1 ; q.addtoq(s); s = test2 ; q.addtoq(s); while(!q.isempty()) q.deletefromq(); :FifoQ tail head :Node2 next content prev test1 test2 s 60

Example q FifoQ q; q = new FifoQ(); String s; s = test1 ; q.addtoq(s); s = test2 ; q.addtoq(s); while(!q.isempty()) q.deletefromq(); :FifoQ tail head :Node2 next content prev :Node2 next content prev test1 test2 s 60

Example q FifoQ q; q = new FifoQ(); String s; s = test1 ; q.addtoq(s); s = test2 ; q.addtoq(s); while(!q.isempty()) q.deletefromq(); :FifoQ tail head :Node2 next content prev :Node2 next content prev test1 test2 s 60

Example q FifoQ q; q = new FifoQ(); String s; s = test1 ; q.addtoq(s); s = test2 ; q.addtoq(s); while(!q.isempty()) q.deletefromq(); :FifoQ tail head :Node2 next content prev :Node2 next content prev test1 test2 s 60

Example q FifoQ q; q = new FifoQ(); String s; s = test1 ; q.addtoq(s); s = test2 ; q.addtoq(s); while(!q.isempty()) q.deletefromq(); :FifoQ tail head :Node2 next content prev :Node2 next content prev test1 test2 61

Example q FifoQ q; q = new FifoQ(); String s; s = test1 ; q.addtoq(s); s = test2 ; q.addtoq(s); while(!q.isempty()) q.deletefromq(); :FifoQ tail head :Node2 next content prev :Node2 next content prev test1 test2 61

Example q FifoQ q; q = new FifoQ(); String s; s = test1 ; q.addtoq(s); s = test2 ; q.addtoq(s); while(!q.isempty()) q.deletefromq(); :FifoQ tail head :Node2 next content prev :Node2 next content prev test1 test2 61

Example q :FifoQ FifoQ q; q = new FifoQ(); String s; s = test1 ; q.addtoq(s); s = test2 ; q.addtoq(s); while(!q.isempty()) q.deletefromq(); tail head :Node2 next content prev test2 61

Example q :FifoQ FifoQ q; q = new FifoQ(); String s; s = test1 ; q.addtoq(s); s = test2 ; q.addtoq(s); while(!q.isempty()) q.deletefromq(); tail head :Node2 next content prev test2 62

Example q :FifoQ FifoQ q; q = new FifoQ(); String s; s = test1 ; q.addtoq(s); s = test2 ; q.addtoq(s); while(!q.isempty()) q.deletefromq(); tail head :Node2 next content prev test2 62

Example q :FifoQ FifoQ q; q = new FifoQ(); String s; s = test1 ; q.addtoq(s); s = test2 ; q.addtoq(s); while(!q.isempty()) q.deletefromq(); tail head :Node2 next content prev test2 62

Example q :FifoQ FifoQ q; q = new FifoQ(); String s; s = test1 ; q.addtoq(s); s = test2 ; q.addtoq(s); while(!q.isempty()) q.deletefromq(); tail head 62

Quiz Give two differences between interfaces and inheritance in Java. 63

Problem Statement Write an application that reads in a text file organized in the manner shown below and displays the final course grades.the course grades are computed differently for the undergraduate and graduate students based on the formulas listed on page 710. The input text file format is as follows: A single line is used for information on one student. Each line uses the format <Type> <Name> <Test 1> <Test 2> <Test 3> where <Type> designates either a graduate or an undergraduate student,<name> designates the student s first and last name, and <Test i> designates the ith test score. of the End of input is designated by the word END. The case letters is insignificant. 64

Overall Plan Tasks Read an input file Compute the course grades Print out the result Input file format: <Type> <Name> <Test 1> <Test 2> <Test 3> U John Doe 87 78 90 G Jill Jones 90 95 87 G Jack Smith 67 77 68 U Mary Hines 80 85 80 U Mick Taylor 76 69 79 END 65

Development Steps We will develop this program in five steps: 1. Start with the program skeleton.define the skeleton ComputeGrades classes. 2. Implement the printresult method.define any other methods necessary to implement printresult. 3. Implement the computegrade method.define any other methods necessary to implement computegrade. 4. Implement the readdata method.define any other methods necessary to implement readdata. 5. Finalize and look for improvements. 66

Step 1 Design We start with a program skeleton. We will define two constructors so the programmer can create a roster of default size or the size of her choice. 67

Step 1 Code Program source file is too big to list here. From now on, we ask you to view the source files using your Java IDE. Directory: Chapter13/Step1 Source Files: ComputeGrades.java 68

Step 1 Test We include a temporary output statement inside the (currently stub) method we define. We run the test main class and verify that the methods are called correctly. 69

Step 2 Design We design and implement the printresult method We use the helper class OutputBox for displaying the result. for each element i in the roster array { output the name of roster[i]; output the test scores of roster[i]; output the course grade of roster[i]; skip to the next line; 70

Step 2 Code Directory: Chapter13/Step2 Source Files: ComputeGrades.java 71

Step 2 Test We verify the temporary readdata method is working correctly. This confirms that we are using the correct student classes and using their methods correctly. We verify the printresult method does indeed display the data in our desired format. 72

Step 3 Design 73

Step 3 Design We design and implement the computegrade method. 73

Step 3 Design We design and implement the computegrade method. The code for actually determining the course grade is embedded in individual student classes 73

Step 3 Design We design and implement the computegrade method. The code for actually determining the course grade is embedded in individual student classes So the code to add to the ComputeGrades class is very simplistic. 73

Step 3 Design We design and implement the computegrade method. The code for actually determining the course grade is embedded in individual student classes So the code to add to the ComputeGrades class is very simplistic. This is a direct benefit of using polymorphism effectively. 73

Step 3 Code Directory: Chapter13/Step3 Source Files: ComputeGrades.java 74

Step 3 Test We will repeat the same test routines from Step 2. Instead of seeing four asterisks, we should be seeing the correct grades. We test both the passing and not passing test scores. 75

Step 4 Design We design and implement the core functionality of the program the readdata method We can express its logic as get the filename from the user; if (the filename is provided) read in data and build the roster array; else output an error message; 76

The buildroster Method set bufreader for input; while (!done ) { line = get next line; if (line is END) { done = true; else { student = createstudent( line ); if (student!= null) { roster[studentcount] = student; //add to roster studentcount++; 77

The buildroster Method The logic of the workhorse private method buildroster is as follows: set bufreader for input; while (!done ) { line = get next line; if (line is END) { done = true; else { student = createstudent( line ); if (student!= null) { roster[studentcount] = student; //add to roster studentcount++; 77

The createstudent Method StringTokenizer parser = new StringTokenizer( line ); String type; try { type = parser.nexttoken(); if (type.equals(under_grad) type.equals(grad)) { student = newstudentwithdata(type, parser); else { //invalid type is encountered student = null; catch (NoSuchElementException e) { //no token student = null; return student; 78

The createstudent Method We use the StringTokenizer class to break down items in a single line of input StringTokenizer parser = new StringTokenizer( line ); String type; try { type = parser.nexttoken(); if (type.equals(under_grad) type.equals(grad)) { student = newstudentwithdata(type, parser); else { //invalid type is encountered student = null; catch (NoSuchElementException e) { //no token student = null; return student; 78

Step 4 Code Directory: Chapter13/Step4 Source Files: ComputeGrades.java 79

Step 4 Test 80

Step 4 Test We run through a more complete testing routine in this step.we need to run the program for various types of input files. Some of the possible file contents are as follows: 80