COMP 114 Weekly Recitation October 10, 2003 Know What’s Happening Monday? first exam The first exam !

Slides:



Advertisements
Similar presentations
SUMMARY: abstract classes and interfaces 1 Make a class abstract so instances of it cannot be created. Make a method abstract so it must be overridden.
Advertisements

Java Review Interface, Casting, Generics, Iterator.
Data Structures Lecture 2 Fang Yu Department of Management Information Systems National Chengchi University Fall 2011.
Written by: Dr. JJ Shepherd
Final Review.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
CSE 143 Lecture 22: Advanced List Implementation (ADTs; interfaces; abstract classes; inner classes; generics; iterators)
Exception handling Dealing with life’s little surprises.
March 2004Object Oriented Design1 Object-Oriented Design.
Arrays  Writing a program that uses a large amount of information.  Such as a list of 100 elements.  It is not practical to declare.
Exceptions Problems with error reporting so far –Either ignored exceptions or terminated program on first error. –Error handling and regular code mixed.
COMP 114 Weekly Recitation November 14, 2003 What’s Happening Monday? Second exam The Second exam !
CPSC150 Abstract Classes and Interfaces Chapter 10.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
Exceptions Problems with error reporting so far –Either ignored exceptions or terminated program on first error. –Error handling and regular code mixed.
Chapter 10 Classes Continued
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter N - 1 Chapter 13 Polymorphism is-a relationships Interfaces.
Abstract Classes and Interfaces
CS221 - Computer Science II Polymorphism 1 Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is.
1 Chapter 8 Objects and Classes. 2 Motivations After learning the preceding chapters, you are capable of solving many programming problems using selections,
CMSC 202 Interfaces. 11/20102 Classes and Methods When a class defines its methods as public, it describes how the class user interacts with the method.
Classes, Objects, Arrays, Collections and Autoboxing Dr. Andrew Wallace PhD BEng(hons) EurIng
Java and C++, The Difference An introduction Unit - 00.
220 FINAL TEST REVIEW SESSION Omar Abdelwahab. INHERITANCE AND POLYMORPHISM Suppose you have a class FunClass with public methods show, tell, and smile.
Recap (önemli noktaları yinelemek) from last week Paradigm Kay’s Description Intro to Objects Messages / Interconnections Information Hiding Classes Inheritance.
Object Oriented Programming: Java Edition By: Samuel Robinson.
2000 Jordan Anastasiade. All rights reserved. 1 Class In this lesson you will be learning about: Class. Inheritance. Polymorphism. Nested and.
The Java Programming Language
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.
Chapter 2: Java Fundamentals
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
JAVA COURSE LESSON2 BY OMPUTER ENGINEEING ASSOCIATION.
1 final (the keyword, not the exam). 2 Motivation Suppose we’ve defined an Employee class, and we don’t want someone to come along and muck it up  E.g.,
 Definition: Accessing child class methods through a parent object  Example: Child class overrides default parent class methods  Example: Child 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.
CSE 143 Lecture 24 Advanced collection classes (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, , slides.
Programming With Java ICS201 University Of Ha’il1 Chapter 7 Inheritance.
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 
Programming and Problem Solving With Java Copyright 1999, James M. Slack Exceptions Handling Exceptions with try and catch The finally-block The throws.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
SOEN 343 Software Design Section H Fall 2006 Dr Greg Butler
Interfaces and Inner Classes
Nested Classes CompSci 230 S Software Construction.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Written by: Dr. JJ Shepherd
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
Inheritance ndex.html ndex.htmland “Java.
OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 3 – Extending classes.
OOP Basics Classes & Methods (c) IDMS/SQL News
David Evans CS201j: Engineering Software University of Virginia Computer Science Lecture 10: Programming Exceptionally.
Important Annoucement 1  I messed up something in the last class  if a subclass overrides a method that throws an exception then it must either 1. throw.
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
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;
Advanced Programming Practice Questions Advanced Programming. All slides copyright: Chetan Arora.
9.1 CLASS (STATIC) VARIABLES AND METHODS Defining classes is only one aspect of object-oriented programming. The real power of object-oriented programming.
Geoff Holmes and Bernhard Pfahringer COMP206-08S General Programming 2.
Sixth Lecture ArrayList Abstract Class and Interface
JAVA MULTIPLE CHOICE QUESTION.
Lecture 2: Data Types, Variables, Operators, and Expressions
University of Central Florida COP 3330 Object Oriented Programming
Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is new code that reuses old code. Polymorphism.
null, true, and false are also reserved.
CMSC 202 Interfaces.
Java Programming Language
Introduction to Java Programming
Review: libraries and packages
Agenda Types and identifiers Practice Assignment Keywords in Java
Topics OOP Review Inheritance Review Abstract Classes
CMSC 202 Interfaces.
Presentation transcript:

COMP 114 Weekly Recitation October 10, 2003

Know What’s Happening Monday? first exam The first exam !

So What’s Happening Today? old midterm We’ll review an old midterm!

With a Special Bonus…...specifically for Kimberly’s section! Flowers! OK, a flower. Right, now back to work.

Question 1A Explain the advantages of writing modular programs. Modular programs are easier to read, debug, and extend since they deal with smaller parts.

Question 1B Explain the difference between an interface and a class. Interfaces can have only method headers, must be implemented by other classes, and cannot be directly instantiated.

Question 1C Why are interfaces useful? Program Evolution: We can replace an obsolete class with a newer one implementing the same interface. Polymorphic Code: By implementing multiple interfaces we can reuse code in differing parts of the program.

Question 2 Consider the following code: package oo; public interface I { public void print(); } package oo; public class C1 implements I { protected static int i = 0; protected int j = 0; public C1(int k) {i = k; j = k;} public void print () { System.out.println (i); System.out.println (j); } package oo; public class C2 extends C1 { public C2 (int k) {super (k);}; public void print() { System.out.println(j); }; } package oo; class M { public static void main (String args[]) { I i1 = new C1(1); I i2 = new C2(2); i1.print(); i2.print(); }

Question 2A What are the class and instance variables? package oo; public interface I { public void print(); } package oo; public class C1 implements I { protected static int i = 0; protected int j = 0; public C1(int k) {i = k; j = k;} public void print () { System.out.println (i); System.out.println (j); } package oo; public class C2 extends C1 { public C2 (int k) {super (k);}; public void print() { System.out.println(j); }; } package oo; class M { public static void main (String args[]) { I i1 = new C1(1); I i2 = new C2(2); i1.print(); i2.print(); }

Question 2B Name the “is-a” relationships in this code. package oo; public interface I { public void print(); } package oo; public class C1 implements I { protected static int i = 0; protected int j = 0; public C1(int k) {i = k; j = k;} public void print () { System.out.println (i); System.out.println (j); } package oo; public class C2 extends C1 { public C2 (int k) {super (k);}; public void print() { System.out.println(j); }; } package oo; class M { public static void main (String args[]) { I i1 = new C1(1); I i2 = new C2(2); i1.print(); i2.print(); }

Question 2C What is the output of this program? package oo; public interface I { public void print(); } package oo; public class C1 implements I { protected static int i = 0; protected int j = 0; public C1(int k) {i = k; j = k;} public void print () { System.out.println (i); System.out.println (j); } package oo; public class C2 extends C1 { public C2 (int k) {super (k);}; public void print() { System.out.println(j); }; } package oo; class M { public static void main (String args[]) { I i1 = new C1(1); I i2 = new C2(2); i1.print(); i2.print(); }

Question 3 package ex; import java.util.NoSuchElementException; public class AnEmptyEnumerationException extends NoSuchElementException {}; package ex; import java.util.Vector; import java.util.Enumeration; import java.util.NoSuchElementException; class AnExceptionThrower { public static void main (String args[]) { Vector v = new Vector (); // create empty vector try { printFirstAndSecondElements(v.elements()); } catch (NoSuchElementException nsee) { System.out.println("Missing first or second vector element."); } v.addElement("hello"); printFirstAndSecondElements(v.elements()); } public static void printFirstAndSecondElements(Enumeration elements) throws AnEmptyEnumerationException, NoSuchElementException { try { System.out.println(elements.nextElem ent().toString()); } catch (NoSuchElementException nsee) { System.out.println("Enumeration is empty"); throw new AnEmptyEnumerationException(); } System.out.println (elements.nextElement().toString()); } What output does this program produce? You don’t have to memorize the system error message, but you should write that one will show up onscreen.

Question 4 Find the syntax errors: package err; public interface I { public int read(); } package err; public abstract class C1 implements I { private int i; } package err; import java.io.IOException; public class C2 extends C1 { protected int j; public C2 (int k) {super (k); j = k; i = k;}; public int read() throws IOException { return System.in.read(); }; } package err; public class ErrorsMain { int i = 0; public static void main(String args[]) { C1 c1 = new C2(1); C2 c2 = new C1(); i = System.in.read(); } C1 implements I but doesn’t offer int read() ErrorsMain.main should have throws IOException C2 can’t call C1(int) since none exists C2 can’t access i since it’s private C1() can’t create a C2 C1 is abstract and can’t be instantiated i is nonstatic and can’t be mentioned in main(String[])

Question 5 Improve the following code. You may not remove external interfaces, but may add to or enhance existing ones. package decr; public class ADecrementableInt { int i; public ADecrementableInt (int newVal) {i = newVal;} public void decrementInt() { i = i - 1;} } package decr; import java.util.Vector; public class ADecrementableVector { Vector v; public ADecrementableVector (Vector newVal) {v = newVal;} // removeElementAt(index) throws ArrayIndexOutOfBoundsException if there is no element at index public void decrementVector() {v.removeElementAt(0);} } package main; import decr.ADecrementableInt; import decr.ADecrementableVector; import java.util.Vector; class ADecrementer { public static void main (String args[]) { ADecrementableVector decrementableVector = new ADecrementableVector(new Vector()); ADecrementableInt decrementableInt = new ADecrementableInt (0); doDecrement (decrementableVector); doDecrement (decrementableInt); } public static void doDecrement (Object o) { if (o instanceof ADecrementableInt) ((ADecrementableInt) o).decrementInt(); else if (o instanceof ADecrementableVector) ((ADecrementableVector) o).decrementVector(); }

Question 5 So what should we do with this mess? Create a common Decrementable interface; get rid of instanceof checks Make ADecrementableInt.i protected Throw a more sensible exception when decrementing an empty vector

Question 5 The final code: package decrement; public interface Decrementable { public void decrement() throws ADecrementException; } package decrement; public class ADecrementException extends Exception { }; package decrement; public class ADecrementableInt implements Decrementable { protected int i; public ADecrementableInt (int newVal) {i = newVal;} public void decrement () { i = i - 1;} } package decrement; import java.util.Vector; public class AdecrementableVector implements Decrementable { protected Vector v; public ADecrementableVector (Vector newVal) {v = newVal;} // removeElementAt(index) throws ArrayIndexOutOfBoundsException if there is no element at index public void decrement () throws ADecrementException { try { v.removeElementAt(0); } catch (ArrayIndexOutOfBoundsException aibe) { System.out.println (“Trying to decrement empty vector”); throw new ADecrementException(); } package main; import decrement.ADecrementableInt; import decrement.ADecrementableVector; import decrement.Decerementable; import java.util.Vector; class ADecrementer { public static void main (String args[]) { ADecrementableVector decrementableVector = new ADecrementableVector(new Vector()); ADecrementableInt decrementableInt = new ADecrementableInt (0); doDecrement (decrementableVector); doDecrement (decrementableInt); } public static void doDecrement (Decrementable d) { try { d.decrement(); catch (ADecrementException de) { System.out.println(“Decrement Underflow”); }

Question 6 Code a class, AScoresTable, that defines a table of names and scores. Its constructor expects an enumeration in which instances of names and scores alternate. A name is represented by a String instance and a score by an Integer instance. Both String and Integer are existing Java classes. (Recall that Integer is the wrapper class provided by Java for the primitive type int.) Thus, the constructor expects a sequence of zero or more ( String, Integer ) pairs. It constructs from this sequence a table consisting of two vectors, names and scores, ensuring that the String and Integer of the ith pair in the enumeration are stored in the ith elements of names and scores, respectively. Thus, assuming the enumeration {“Joe Doe” 50 “Jane Smith” 60}, it constructs the vectors {“Joe Doe” “Jane Smith”} and {50 60}. In case of a parsing error, it throws AParsingException to its caller. A partial implementation of the class is given below. Complete the class by implementing the method setNamesAndScores(Enumeration ). You may use recursion or a loop. package scores; public class AParsingException extends java.io.IOException {}; package scores; import java.util.Vector; import java.util.Enumeration; public class AScoreTable { Vector names = new Vector(); Vector scores = new Vector(); public AScoreTable (Enumeration enumeration) throws AParsingException {setNamesAndScores (enumeration);} //you need to implement the following method public void setNamesAndScores (Enumeration enumeration) throws AParsingException { while (enumeration.hasMoreElements()) try { names.addElement((String) enumeration.nextElement()); scores.addElement((Integer) enumeration.nextElement()); } catch (ClassCastException cce) { throw new AParsingException(); } catch (NoSuchElementException nsee) { throw new AParsingException() } } }

Question 1. Or Question 7. Consider the following two classes, ASingleQuotedString and ADoubleQuotedString: public class ASingleQuotedString { protected String string; public ASingleQuotedString (String theString) {string = theString;}; public String getString() {return string;} public String getQuotedString() {return '\'' + string + '\'';}; } public class ADoubleQuotedString { protected String string; public ADoubleQuotedString (String theString) {string = theString;}; public String getString() {return string;} public String getQuotedString() {return '\"' + string + '\"';} } Factor the code in these classes by defining a new abstract class, AnAbstractQuotedString; and two new concrete subclasses, AConcreteSingleQuotedString, and AConcreteDoubleQuotedString. The two concrete subclasses should have the same behavior as the two original classes and you should factor out as many methods and as much code as possible into the abstract class. In the process of factoring you should try to maintain strong encapsulation, that is, not access variables declared in other classes. You are free to implement new methods.

Question 1. Or Question 7. Part 2. public abstract class AnAbstractQuotedString { protected char quote; protected String string; protected AnAbstractQuotedString(String s, char q) { string = s; quote = q; } public String getString() { return string; } public String getQuotedString() { return quote + string + quote; } } public class ASingleQuotedString extends AnAbstractQuotedString { public ASingleQuotedString(String s) { super(s, '\''); } } public class ADoubleQuotedString extends AnAbstractQuotedString { public ADoubleQuotedString(String s) { super(s, '\"'); } }

Epilogue Any questions about the test? Any comments about Program 3?