Java Peer Instruction Materials Review
Materials by Cynthia Lee under a Creative Commons License discussing Java concepts such as Iterator design pattern, composition vs. inheritance, legality of certain code snippets, and clarity on the accessibility of public and protected class elements to clients. Additionally, a step towards using JUnit for Java unit testing is highlighted.
Download Presentation
Please find below an Image/Link to download the presentation.
The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. Download presentation by click this link. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.
E N D
Presentation Transcript
Creative Commons License CS2 in Java Peer Instruction Materials by Cynthia Lee is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License. Based on a work at http://peerinstruction4cs.org. Permissions beyond the scope of this license may be available at http://peerinstruction4cs.org. CSE 12 Basic Data Structures Cynthia Bailey Lee Some slides and figures adapted from Paul Kube s CSE 12
Reading Quiz! 1) The Iterator design pattern helps you access elements of a Collection, in a way common to all Collections. A. TRUE! B. FALSE!
Reading Quiz! 2) Composition creates an 'is-a' relationship and Inheritance creates a 'has-a' relationship. A. TRUE! B. FALSE!
Reading Quiz! 3) In Java, if A is an Interface, you cannot create a new instance of type A. A. TRUE! B. FALSE!
Review of Thursday: Inheritance! * Types * Visibility
Which is legal? A: Base b=new Base(); Derived d=b; public class Base { protected int x; } B: Derived d=new Derived(); Base b=d; C: Base b=new Derived(); public class Derived extends Base { protected int y; } D: Derived d=new Base(); E: Other/none/more
True, False, or Mostly True Public methods are the only part of your class that clients can access and use. A. TRUE! B. FALSE! C. Mostly! (true but incomplete)
True, False, or Mostly True Public methods are the only part of your class that clients can access and use. C: Mostly (true but incomplete) Clients can also use any public instance variables, and subclasses can use any protected instance variables. Be aware that your clients may create subclasses of your classes!
Step 1 of HW Java s JUnit system
10 Unit testing with the swingui of Junit 3.8.1: all tests passed The green bar of happiness; all tests passed! Names of the testing methods corresponding to the test cases you prepared. A green check mark means the test passed.
When one or more tests fail The red bar of sadness; some tests failed Names of the testing methods in your test suite. A red X means the test failed. Stack trace telling what was expected, what was generated and where the test failed; very handy!
12 JUnit basics To do unit testing in the Junit framework: Define a subclass of junit.framework.TestCase Optional: Define instance variables that store the state of the test fixture , i.e. the objects that will be tested Initialize the fixture state by overriding the setUp() instance method Clean-up the fixture state after a test by overriding the tearDown() instance method Define public void no-argument methods with names that start with test. Each testXXX method should be written to test a particular aspect of the test fixture Define a main() method to run your TestCase class as a program
TestCase and test fixtures Define a subclass of junit.framework.TestCase Define instance variables that store the state of the test fixture , i.e. the objects that will be tested import junit.framework.*; To inherit the testing and test run methods we will need public class RectangleTester extends TestCase { private Rectangle r1, r2; // test fixtures
setUp() and tearDown() /* Called AUTOMATICALLY before each testXXX() method is run */ protected void setUp() { r1 = new Rectangle(); r2 = new Rectangle(2.0,3.0); } Make sure each test method starts with a clean copy of the test fixture. /* Called AUTOMATICALLY after each testXXX() method is run */ protected void tearDown() { r1 = null; r2 = null; } setup(); testXXX(); teardown(); This is the sequence of calls the JUnit framework does for you automatically for each test method testXXX() that is invoked.
Coding a test case as a testXXX method /** Test case 2.1: verify that default constructor sets default instance variable values correctly */ public void testDefaultInstance() { assertEquals(1.0,r1.getLength()); assertEquals(1.0,r1.getHeight()); } Remember: setUp() will be called prior to each test method getting called, creating test object r1 anew for each test /** Test case 2.6: verify that mutator for length throws * exception on illegal input. */ public void testMutatorIllegalInput() { try { r1.setLength(0); // 0 is illegal, should throw fail(); } catch (IllegalArgumentException e) { // test passes } }
16 Running your TestCase class To run a class as a program, the class must have a public static void main() method. Here are two ways to define it in the Junit 3.8.1 framework, depending on whether you want a GUI or text version: /** Run RectangleTester as a gui application */ public static void main(String args[]) { junit.swingui.TestRunner.main(new String[] { RectangleTester }); } /** Run RectangleTester as a text console application */ public static void main(String args[]) { junit.textui.TestRunner.main(new String[] { RectangleTester }); }
17 More JUnit basics Test fixture instance variables are optional: you can do the same thing with local variables inside the test methods If you are not using test fixture instance variables, you do not need to define setUp() and tearDown() either When you run your TestCase class as a program, each testXXX method is called automatically If a Junit assertion fails when a testXXX method runs, that test fails If testXXX method throws an exception, that is considered an error, not a test failure! If a testXXX method returns normally, that test passes
18 JUnit 3.8.1 assertion methods The JUnit framework provides many useful assertion methods to use in your testXXX() methods assertEquals(x,y) // fail if x is not equal to y assertTrue(b) // fail if b has boolean value false assertFalse(b) // fail if b has boolean value true assertSame(x,y) // fail if x and y point to different objects assertNotSame(x,y) // fail if x and y point to the same object assertNull(x) // fail if x is not null assertNotNull(x) // fail if x is null fail() // always fails All these assertion methods are overloaded with a version that takes an additional first argument of type String, a message which will be printed out in some contexts
Consider the following class for a Ninja public class Ninja { private int honor; public Ninja(int h) { this.honor=h; } }
Using the Ninja class: Ninja n1=new Ninja(50); Ninja n2=new Ninja(50); n1 n2 honor: 50 honor: 50
n1 n2 honor: 50 honor: 50 True, False, or It Depends? n1 == n2 A: True B: False C: It Depends
n1 n2 honor: 50 honor: 50 True, False, or It Depends? n1.equals(n2) A: True B: False C: It Depends
Default implementation of equals() in the Java source code: public boolean equals(Object obj) { return (this == obj); } If you don't override equals, this is the default version you inherit! Which is really same as using ==
Improved Ninja class public class Ninja { private int honor; public Ninja(int h) { this.honor=h; } public boolean equals(Ninja other) { return this.honor == other.honor; } }
n1 n2 honor: 50 honor: 50 Using the improved Ninja class n1.equals(n2) is now True!
True, False, or It Depends? Object o1=new Ninja(50); Ninja n2=new Ninja(50); o1.equals(n2); A: True B: False C: It Depends
You must override the equals() method inherited from Object! public class Ninja { ... public boolean equals(Object other) { if (!(other instanceof Ninja)) { return false; } Ninja o=(Ninja)other; return this.honor == o.honor; } }
Iterators Next!
The Iterator Software Design Pattern A common situation: A client needs to inspect the data elements in a collection, without wanting to know details of how the collection structures its data internally Solution: Define an interface that specifies how an iterator will behave Design the collection to be able to supply an object that implements that iterator interface A client then can ask the collection for an iterator object, and use that iterator to inspect the collection s elements, without having to know how the collection is implemented
4-31/36 Iterable<E> Interface TheCollection<E>interface extends the Iterable<E>interface, which is defined as follows: public interface Iterable<E> { public Iterator<E> iterator(); } So any class that implements Collection<E>must define an instance method iterator() that returns an Iterator<E>object for that instance And Iterator<E> is also an interface in the JCF
4-32/36 Iterator<E> Interface TheIterator<E>interface is defined as follows: public interface Iterator<E> { public E next(); public boolean hasNext(); public void remove(); } So, any object that is-a Iterator<E> will have those operations as part of its API. But what are these methods supposed to do? Let s look at the documentation, and some examples
WHY have iterators? What is the difference between these codes? Note: ls is some object of a type that implements List<MyObjs> Iterator version Iterator<MyObjs> i = ls.iterator(); while (i.hasNext()) { MyObjs x = i.next(); //do something with x } A. No difference: they are totally equivalent B. Difference: Increment will run faster C. Difference: Iterator will run faster D. No difference: Java just likes having iterators to make students lives harder E. Other/none/more Increment version int i=0; while (i<c.size()) { MyObjs x = ls.get(i); //do something with x i++; }
WHY have iterators? Linked List To go to nth element, you must start at the beginning and go through one at a time until you get to the nth one A pain to start over vs just having the iterator keep your place like a bookmark Trees To go to the nth element, you must travel around the tree in some planned way A pain to start over vs just having the iterator keep your place in the journey