ITI 1221. Introduction to Computing II Lab-6 Dewan Tanvir Ahmed University of Ottawa.

Slides:



Advertisements
Similar presentations
AITI Lecture 19 Linked List Adapted from MIT Course 1.00 Spring 2003 Lecture 26 and Tutorial Note 9 (Teachers: Please do not erase the above note)
Advertisements

CS 206 Introduction to Computer Science II 09 / 05 / 2008 Instructor: Michael Eckmann.
INHERITANCE BASICS Reusability is achieved by INHERITANCE
Written by: Dr. JJ Shepherd
Road Map Introduction to object oriented programming. Classes
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
School of Computing Science CMT1000 © Ed Currie Middlesex University Lecture 9: 1 CMT1000: Introduction to Programming Ed Currie Lecture 11: Objects.
Unit 11 1 Unit 11: Data Structures H We explore some simple techniques for organizing and managing information H This unit focuses on: Abstract Data Types.
The List Interface Cmput Lecture 14 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture is based.
CS 106 Introduction to Computer Science I 04 / 30 / 2010 Instructor: Michael Eckmann.
CSC3170 Introduction to Database Systems
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Summary and Exam COMP 102.
CSC 212 – Data Structures Lecture 12: Java Review.
Object Oriented Design: Identifying Objects
1 Object-Oriented Software Engineering CS Interfaces Interfaces are contracts Contracts between software groups Defines how software interacts with.
Announcements  I will discuss the labtest and the written test #2 common mistakes, solution, etc. in the next class  not today as I am still waiting.
Polymorphism, Inheritance Pt. 1 COMP 401, Fall 2014 Lecture 7 9/9/2014.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Comments, Variables, etc.)
ITI Introduction to Computing II Lab-8 Dewan Tanvir Ahmed University of Ottawa.
Java Quiz Bowl A fun review of the Java you should know from CMPT 201 If you don’t know the answers - this week is for you to study up!
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
1 Abstract Classes “I prefer Agassiz in the abstract, rather than in the concrete.” CS Computer Science II.
Programming With Java ICS201 1 Chapter 14 Generics and The ArrayList Class.
ArrayList Class An ArrayList is an object that contains a sequence of elements that are ordered by position. An ArrayList is an object that contains a.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 5 Generic.
Chapter 10 Defining Classes. The Internal Structure of Classes and Objects Object – collection of data and operations, in which the data can be accessed.
4-1 Topic 6 Linked Data Structures. 4-2 Objectives Describe linked structures Compare linked structures to array- based structures Explore the techniques.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
Objects & Classes Weiss ch. 3. So far: –Point (see java.awt.Point) –String –Arrays of various kinds –IPAddress (see java.net.InetAddress) The Java API.
ITI Introduction to Computing II Lab-7 Dewan Tanvir Ahmed University of Ottawa.
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
U n i v e r s i t y o f H a i l 1 ICS 202  2011 spring  Data Structures and Algorithms 
Chapter 7: Class Inheritance F Superclasses and Subclasses F Keywords: super and this F Overriding methods F The Object Class F Modifiers: protected, final.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
1 Java linked list. Java linked list - definition ▪ Often in programming we are required to systematically store some type of information. A prime example.
Interfaces and Inner Classes
Iterators ITI 1121 N. El Kadri. Motivation Given a (singly) linked-list implementation of the interface List, defined as follows, public interface List.
Written by: Dr. JJ Shepherd
ITI Introduction to Computing II Lab-5 Dewan Tanvir Ahmed University of Ottawa.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Java linked list.
OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 3 – Extending classes.
Unified Modeling Language (UML)
Session 7 More Implications of Inheritance & Chapter 5: Ball World Example.
Stacks – Cont’d Nour El-Kadri ITI Summary We have seen that arrays are efficient data structures. Accessing any element of an array necessitates.
Arrays, Link Lists, and Recursion Chapter 3. Sorting Arrays: Insertion Sort Insertion Sort: Insertion sort is an elementary sorting algorithm that sorts.
Last Revision. Question1 Novice Java programmers often write code similar to, class C { public int x;... }... C[] a = new C[10]; for(int i = 0; i < a.length;
CS100Lecture 61 Announcements Homework P1 due on Thursday Homework P2 handed out.
The need for Programming Languages
CHAPTER 4: Linked Structures
Lecture 12 Inheritance.
Software Development Java Classes and Methods
03/10/14 Inheritance-2.
Lecture 2: Data Types, Variables, Operators, and Expressions
Exceptions, Interfaces & Generics
Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is new code that reuses old code. Polymorphism.
Class Inheritance (Cont.)
Paul Ammann & Jeff Offutt
null, true, and false are also reserved.
Introduction to Java Programming
An Introduction to Java – Part I, language basics
Chapter 11: More on the Implications of Inheritance
Collections Framework
ITI Introduction to Computing II Lab-12
Agenda Types and identifiers Practice Assignment Keywords in Java
Presentation transcript:

ITI Introduction to Computing II Lab-6 Dewan Tanvir Ahmed University of Ottawa

Today’s Objective  Further understanding of linked structures  Review of the concepts of interface and inheritance  Questions and answers

LinkedPair  A class that represents a pair of Objects oFirst element oSecond element  For example: ( “computer”, “science” ) o“computer” is the first element o“science” is the second element  Either references might be null o( null, “hello” ) o( “hello”, null ) o( null, null )

LinkedPair – Interface Pair  Write an interface, Pair, that can hold a pair of Objects. It includes ogetFirst  It returns the first element in p  Example, p.getFirst() ogetSecond  It returns the second element in p oSwap  It changes the order of the elements in p.  For example if p is the pair ( “computer”, “science” ), p.swap() would change p to be the pair ( “science”, “computer” ). public interface Pair { public abstract Object getFirst(); public abstract Object getSecond(); public abstract void swap(); }

LinkedPair (cont..)  Create a class called LinkedPair which implements the interface Pair, and has the following: oA static nested class Elem private static class Elem { private Object value; private Elem next; private Elem( Object value, Elem next ) { this.value = value; this.next = next; } }

LinkedPair (cont..) oThe instance variable first  points to the node containing the first element in the pair and  that node points to another node containing the second element in the pair. oA constructor with 2 parameters, both Objects,  which are used as the first and second elements in the new Pair instance. public class LinkedPair implements Pair { private static class Elem { … } private Elem first; public LinkedPair( Object first, Object second ) { this.first = new Elem( first, new Elem( second, null ) ); } public Object getFirst() { return first.value; } public Object getSecond() { return first.next.value; } }

LinkedPair (cont..) oswap() method must work by changing the pointers that define the node order, it must not simply swap the values that are stored in the two nodes. public void swap() { Elem newFirst = first.next; newFirst.next = first; first.next = null; first = newFirst; } public String toString() { return "(" + first.value + "," + first.next.value + ")"; }

LinkedPair (cont..)  Add a method equals such that: oIf p1 and p2 are two objects implementing Pair, op1.equals( p2 )  returns true if each element in p1 is equal to the corresponding element in p2, and  returns false otherwise. oThis method must handle the case when p2 is null. oQuestion: what if p1 is null?

LinkedPair (cont..) public boolean equals( Object obj ) { if ( obj == null || ! ( obj instanceof Pair ) ) return false; Pair other = (Pair) obj; boolean firstEquals = false; if ( getFirst() == null && other.getFirst() == null ) { firstEquals = true; } else if ( getFirst() != null && getFirst().equals( other.getFirst() ) ) { firstEquals = true; } boolean secondEquals = false; if ( getSecond() == null && other.getSecond() == null ) { secondEquals = true; } else if ( getSecond() != null && getSecond().equals( other.getSecond() ) ) { secondEquals = true; } return firstEquals && secondEquals; }

LinkedPair (cont..)  Create a test class for your implementation, call it TestPair.  Play with this class class TestPair { public static void main( String[] args ) { Pair a = new LinkedPair( "computer", "science" ); System.out.println( a ); a.swap(); System.out.println( a ); Pair b = new LinkedPair( "computer", "science" ); if ( a.equals( b ) ) { System.out.println( "failed" ); } b.swap(); … }

LinkedPair (cont..) - Alternative  Create a new class Elem such that the class Elem is a top-level class (i.e. create a new file called Elem to implement the nodes of the linked structure).  Make the visibility of the class package and make its instance variable protected class Elem { protected Object value; protected Elem next; protected Elem( Object value, Elem next ) { this.value = value; this.next = next; } }

LinkedElems public class LinkedElems { private static class Elem { … } public static boolean equals( Elem p, Elem q ) { if ( p == null && q == null ) return true; Elem pp = p; Elem qq = q; boolean result = ( pp != null ) && ( qq != null ); while ( result && pp != null ) { if ( qq == null ) { result = false; // q is shorter than p } else if ( pp.value == null && qq.value != null ) { result = false; } else if ( pp.value != null && ( ! pp.value.equals( qq.value ) ) ) { result = false; } else { pp = pp.next; qq = qq.next; } if ( pp == null && qq != null ) { result = false; // p is shorter than q } return result; }

LinkedElems (cont..) public static void main( String[] args ) { Elem p; p = new Elem( "A", null ); p.next = new Elem( new Integer( 3 ), null ); p.next.next = new Elem( new Boolean( true ), null ); Elem q; q = new Elem( "A", new Elem( new Integer( 3 ), null ) ); if ( equals( p, q ) ) { System.out.println( "[1] failed" ); } q.next.next = new Elem( new Boolean( true ), null ); if ( ! equals( p, q ) ) { System.out.println( "[2] failed" ); }

LinkedPair (cont..) - Alternative  Modify the class Elem so that the instance variables are private. You will be forced to create access methods, getters and setters. public class Elem { private Object value; private Elem next; public Elem( Object value, Elem next ) { this.value = value; this.next = next; } public Object getValue() { return value; } public void setValue( Object value ) { this.value = value; } public Elem getNext() { return next; } public void setNext( Elem next ) { this.next = next; }

Inheritance – Once again  The company Java Financial Solutions is developing a new software system for tracking professional expenses.  You are part of the software development team responsible for the hierarchy of classes to represent expenses.

Inheritance – Once again  All expenses have a description (a character string)  All the transportation expenses have a destination (a character string)  A transportation expense using a private car has a distance (of type int)  A transportation expense by air has a fixed amount (of type double) specified when a new transportation expense is created  All the meal expenses have an attribute which represents the number of meals  All the expenses have a method to calculate the amount represented by this expense: oThe amount for a transportation expense using a private car is a fixed rate times the distance traveled oThe amount for a transportation expense by air is a fixed amount (specified when a new transportation expense is created) oThe amount for a meal expense is the number of meals times a fixed rate. The rate depends on the kind of meal: Breakfast, Lunch or Dinner

Inheritance – Once again  Class Expense (abstract class): o An instance variable for description o Constructor with one parameter for description initial value o Access method for description o An abstract method to get the amount of the expense public abstract class Expense { private String description; public Expense( String description ) { this.description = description; } public String getDescription() { return description; } public abstract double getAmount(); }

Inheritance – Once again  Class Transportation (an abstract extension of the class Expense): oAn instance variable for destination oConstructor with one extra parameter for destination initial value public abstract class Transportation extends Expense { private String destination; public Transportation( String description, String destination ) { super( description ); this.destination = destination; }

Inheritance – Once again  Class Meal (an abstract extension of the class Expense): oAn instance variable for the number of meals oConstructor with one extra parameter for number of meals initial value oAccess method for the number of meals oImplementation of getAmount() method. The amount for a meal expense is the number of meals times a fixed rate oAn abstract method for getting the rate. The rate depends on the kind of meal: Breakfast, Lunch or Dinner public abstract class Meal extends Expense { private int numberOfMeals; public Meal( String description, int numberOfMeals ) { super( description ); this.numberOfMeals = numberOfMeals; } public int getNumberOfMeals() { return numberOfMeals; } public double getAmount() { return getNumberOfMeals() * getRate(); } public abstract double getRate(); }

Inheritance – Once again  Class PrivateCar (an extension of the class Transportation): o A static variable for the rate (0.427) o An instance variable for the distance o Constructor with one extra parameter for distance initial value o Access method for distance o Implementation of getAmount() method. The amount for a private car expense is the distance times the rate public class PrivateCar extends Transportation { public static double RATE = 0.427; private int distance; public PrivateCar( String description, String destination, int distance ) { super( description, destination ); this.distance = distance; } public int getDistance() { return distance; } public double getAmount() { return distance * RATE; } }

Inheritance – Once again  Class Airfare (an extension of the class Transportation): o An instance variable for the amount o Constructor with one extra parameter for amount initial value o Access method for the amount public class Airfare extends Transportation { public double amount; public Airfare( String description, String destination, double amount ) { super( description, destination ); this.amount = amount; } public double getAmount() { return amount; } }

Inheritance – Once again  Class Breakfast (an extension of the class Meal): o A static variable for the rate (11.55) o Constructor with no extra parameter o Access method for the rate public class Breakfast extends Meal { public static double RATE = 11.55; public Breakfast( String description, int numberOfMeals ) { super( description, numberOfMeals ); } public double getRate() { return RATE; } }

Inheritance – Once again  Class Lunch (an extension of the class Meal): o A static variable for the rate (11.30) o Constructor with no extra parameter o Access method for the rate public class Lunch extends Meal { public static double RATE = 11.30; public Breakfast( String description, int numberOfMeals ) { super( description, numberOfMeals ); } public double getRate() { return RATE; } }

Inheritance – Once again  Class Dinner (an extension of the class Meal): o A static variable for the rate (31.80) o Constructor with no extra parameter o Access method for the rate public class Dinner extends Meal { public static double RATE = 31.80; public Breakfast( String description, int numberOfMeals ) { super( description, numberOfMeals ); } public double getRate() { return RATE; } }

Inheritance – Once again  Class ExpenseTracker  Complete the partial implementation of the class ExpenseTracker  An ExpenseTracker is used to store Expenses: oAdd the type of the elements of the array expenses oComplete the constructor oComplete the implementation of the method double getTotal(). oThe method double getTotal() returns the total amount for all the expenses that are currently stored in the ExpenseTracker

Inheritance – Once again public class ExpenseTracker { private Expense[] expenses; private int size; public ExpenseTracker( int capacity ) { expenses = new Expense[ capacity ]; size = 0; } public boolean add( Expense e ) { expenses[ size++ ] = e; return true; } public double getTotal() { double total = 0.0; for ( int i=0; i<size; i++ ) { total = total + expenses[ i ].getAmount(); } return total; } } }

Inheritance – Once again public class Run { public static void main( String[] args ) { ExpenseTracker epro = new ExpenseTracker( 10 ); epro.add( new PrivateCar( "ACFAS 2004", "Montreal (QC)", 430 ) ); epro.add( new Airfare( "IWBRA 2005", "Atlanta (GA)", ) ); epro.add( new Breakfast( "IWBRA 2005", 2 ) ); epro.add( new Lunch( "IWBRA 2005", 3 ) ); epro.add( new Dinner( "IWBRA 2005", 2 ) ); System.out.println( "total = " + epro.getTotal() ); } } Its output is as follows: total =

The End