CS410J: Advanced Java Programming

Size: px
Start display at page:

Download "CS410J: Advanced Java Programming"

Transcription

1 CS410J: Advanced Java Programming The Dependency Injection design pattern decouples dependent objects so that they may be configured and tested independently. Google Guice manages dependencies among objects and handles the complexity of wiring together complex object relationships. Dependency Injection The Dependency Injection design pattern Testing with mock objects using Mockito Managing dependencies with Google Guice Copyright c by David M. Whitlock. Permission to make digital or hard copies of part or all of this work for personal or classroom use is granted without fee provided that copies are not made or distributed for profit or commercial advantage and that copies bear this notice and full citation on the first page. To copy otherwise, to republish, to post on servers, or to redistribute to lists, requires prior specific permission and/or fee. Request permission to publish from whitlock@cs.pdx.edu. Last updated May 7,

2 Dependencies Among Objects Consider the below set of dependent objects BookInventory remove(book) add(book) instock(book) : int BookStore purchase(list<book>, CreditCard) : double refund(list<book> CreditCard) : double CreditCardService debit(creditcard, dollars : int, cents : int) credit(creditcard, dolars : int, cents : int) BookDatabase directory : File filename : String FirstBankOfPortlandStateServlet REST FirstBankOfPSU serverhost : String serverport : int A BookStore requires a BookInventory and a CreditCardService to get its work done We ve already extracted interfaces to allow us to abstract out the behavior that we need We want to be able to replace the implementations of BookInventory and CreditCardService without affecting the code in BookStore 2

3 How can we implement BookStore? package edu.pdx.cs410j.di; import java.io.file; import java.util.list; public class BookStore { private final BookInventory inventory; private final CreditCardService cardservice; public BookStore() { String tmpdir = System.getProperty( "java.io.tmpdir" ); File directory = new File( tmpdir ); this.inventory = new BookDatabase( directory, "books.txt" ); this.cardservice = new FirstBankOfPSU( "localhost", 8080 ); When the BookStore is created, it also creates its dependencies Dependencies are stored in final fields because they only need to be created once 3

4 How can we implement BookStore? public double purchase( List<Book> books, CreditCard card) { double total = 0.0d; for (Book book : books) { inventory.remove(book); total += book.getprice(); CreditTransactionCode code = cardservice.debit(card, total); if (code == CreditTransactionCode.SUCCESS ) { return total; else { throw new CreditCardTransactionException(code); The purchase method uses the dependencies 4

5 What is wrong with this solution? Sure, this code works, but.. You can t test this code! Tests would have to execute against the actual database (slow) and credit card service ($$$) Lots of data setup: create database file and credit card account The BookStore has to know how to configure its dependencies Does the BookStore really care what port the credit card service runs on? If another class wants to use the BookDatabase, it would have to create another instance Two BookDatabases can t work with the same file If you want to switch out another implementation of the dependencies, you have to change the BookStore Again, does the BookStore really care what kind of BookInventory is uses? 5

6 Don t call us, we ll call you The Hollywood Principle states that dependent code should require that its dependencies are provided to it Practically speaking, it means pass dependencies into the constructor public BookStore( BookInventory inventory, CreditCardService cardservice ) { this.inventory = inventory; this.cardservice = cardservice; Now the BookStore class doesn t have to know about the concrete types of its dependencies Let the main program create and configure dependencies public class BookStoreApp { public static void main(string... args) { String tmpdir = System.getProperty( "java.io.tmpd File directory = new File( tmpdir ); BookInventory inventory = new BookDatabase( directory, "books.txt" ); CreditCardService cardservice = new FirstBankOfPSU( "localhost", 8080 ); BookStore store = new BookStore(inventory, cardservice); 6

7 Testing with Mock Objects Now that a BookStore gets passed its dependencies, you can test the class without using the production BookInventory and CreditCardService Instead of using real dependencies, test with mock objects that provide an implementation of the interface that is useful for testing package edu.pdx.cs410j.di; public abstract class MockObject { protected void shouldnotinvoke() { throw new UnsupportedOperationException( "Did not expect this method to be invoked"); package edu.pdx.cs410j.di; public class MockBookInventory extends MockObject implements BookInventory { public void remove( Book book ) { shouldnotinvoke(); 7

8 Testing with Mock Objects Test that BookStore invokes the expected methods of its dependencies Override interface methods to keep track of how it was invoked package edu.pdx.cs410j.di; import org.junit.test; import java.util.collections; import static org.junit.assert.assertequals; import static org.junit.assert.assertnotnull; public class BookStoreTest public void testbookispurchased() { final Book[] removedbook = new Book[1]; BookInventory inventory = new MockBookInventory() public void remove( Book book ) { removedbook[0] = book; ; CreditCardService cardservice = new MockCreditCar public CreditTransactionCode debit( CreditCard return CreditTransactionCode.SUCCESS; ; 8

9 Testing with Mock Objects Once the mock dependencies are set up Create the BookStore Invoke the method you want to test Verify that the dependency was invoked as you expected BookStore store = new BookStore(inventory, cardservice); CreditCard card = new CreditCard( "123" ); final Book testbook = new Book("title", "author", 1.00d); double total = store.purchase( Collections.singletonList(testBook), card ); assertequals( testbook.getprice(), total, 0.0d ); final Book removed = removedbook[0]; assertnotnull( removed ); assertequals(testbook.gettitle(), removed.gettitl assertequals(testbook.getauthor(), removed.getaut assertequals(testbook.getprice(), removed.getpric 9

10 Mock Objects are Awkward Mock Objects get the job done, but... Lots of verbose boilerplate code When interface changes (new method, e.g.), mock has to change Subclassing mock objects is hokey Lots of anonymous inner classes Have to keep track of state that was passed to dependency There s got to be a better way, right? 10

11 Mock Objects with Mockito There are several testing libraries for Java that allow you to easily create mock objects We re going to learn about Mockito ( A Java API that creates mock objects for interfaces and classes Contains a domain specific language (DSL) for constructing mock objects You can specify what behavior you expect out of the mock objects Add the dependency in your pom.xml <dependency> <groupid>org.mockito</groupid> <artifactid>mockito-core</artifactid> <version>1.8.5</version> <scope>test</scope> </dependency> 11

12 Mock Objects with public void testcreditcardischarged() { Book book = mock(book.class); double price = 1.00d; when( book.getprice() ).thenreturn( price ); BookInventory inventory = mock(bookinventory.class); CreditCardService cardservice = mock(creditcardservice.class); when(cardservice.debit(any( CreditCard.class ), anydouble() )).thenreturn( CreditTransactionCode.SUCCESS ); BookStore store = new BookStore(inventory, cardservice); CreditCard card = mock(creditcard.class); double total = store.purchase( Collections.singletonList(book), card ); assertequals( book.getprice(), total, 0.0d ); verify( cardservice ).debit( card, price ); Let s take a closer look... 12

13 Creating mock objects The most interesting methods are all in the org.mockito.mockito class The mock method creates a mock object for an interface or class static <T> T mock(class<t> classtomock) Unless instructed otherwise, invoking a method of the mock object will noop or return null Mockito uses crazy class loading tricks to accomplish this We mocked all of our objects in the previous example No need to invoke constructors Only had to specify the state we needed The test doesn t care about the title or author of the Book We can add a method to an interface without having to update a mock implementation 13

14 Specifying behavior of mock objects The when method specifies how a method of the mock object should behave static <T> OngoingStubbing<T> when(t methodcall) Because they cannot be overridden by the magical class loader, final methods cannot be sent to when The OngoingStubbing class specifies what the behavior of the mock method thenreturn(t value) will cause the mock method to return a given value thenthrow(throwable t) will throw an exception when the mock method is invoked thencallrealmethod() will invoked the real implementation of the mock object to be invoked In general, you want to chain the when and then calls together when( book.getprice() ).thenreturn( price ); 14

15 Method Argument Matching The same mock method can be configured with different argument values when( cardservice.debit(card, price).thenreturn(success)) when( cardservice.debit(card, -1.0).thenReturn(INVALID_AMOUNT)) Sometimes the behavior of the mock method doesn t depend on the value of its arguments Always return SUCCESS no matter which card is passed in Matchers, the superclass of Mockito, has methods for filtering which values apply to the when Basically, there are bunch of type safe any methods any() object (or null) or any(class<t>) object of a given type anyint(), anydouble(), anystring(), etc. isnull, isnotnull, and same(t), matches(string regex) 15

16 Method Argument Matching If at least one arguments to a mock method is one of the matchers, then all arguments must be matchers Use the eq() methods for matching on a single value when( cardservice.debit( any(creditcard.class), eq(-1.0) ).thenreturn(invalid_amount); The AdditionalMatchers class has even more matchers Boolean operations on matchers: and, or, not, etc. Comparison operations: gt, lt, geq 16

17 Verifying Mock Objects After configuring your mock objects and sending them to the API you want to test, the mock objects are verified Mock objects keep a history of what methods were invoked with which arguments The verify method tests whether or not a mock method was invoked with the expected arguments To verify that cardservice was invoked with the expected card and price: verify( cardservice ).debit( card, price ); You can also use matchers with verify verify(cardservice).debit( same(card), eq(price) ); 17

18 Managing Dependencies As your application scales, wiring together dependencies can become very cumbersome Large initialization code that references tons of classes Difficult to change out old implementations for new implementations End up relying on design patterns to create instances Factory Pattern Create instances of a class using a static method Singleton Pattern Access the one-and-only instance of a class via a static method Lots of boilerplate code that is tricky to get right Concurrent access to singletons Life cycle of pooled/cached objects 18

19 Google Guice Google Guice (pronounced juice ) is a framework for configuring and injecting dependencies into Java classes Leverages annotations to provide type-safety Well-known objects are registered in one place (a module ) Objects that depend on well-known objects are created by Guice via reflection Dependencies are injected into constructors and fields Maven dependency: <dependency> <groupid>com.google.code.guice</groupid> <artifactid>guice</artifactid> <version>2.0</version> </dependency> 19

20 Managing Dependencies without Guice From BookStoreApp.java public static void main(string... args) throws JAXBException, IOException { String tmpdir = System.getProperty("java.io.tmpdir"); File directory = new File(tmpdir); BookInventory inventory = new BookDatabase(directory); addbooks(inventory); CreditCardService cardservice = new FirstBankOfPSU("localhost", 8080); Logger logger = Logger.getLogger("edu.pdx.cs410J.Logger"); logger.setlevel(level.info); CheckoutPanel panel = new CheckoutPanel(inventory,cardService,logger); BookStoreGUI gui = new BookStoreGUI(panel); gui.pack(); gui.setvisible( true ); If we want to introduce another panel that is for inventory control, we d have to pass the well-known BookInventory instance to that code, too. 20

21 Requesting Objects from Guice Annotating one of a class s constructors instructs Guice to invoke that constructor when an instance is requested Guice will provide the well-known instances of the constructors public CheckoutPanel(BookInventory inventory, CreditCardService cardservice, Logger logger ) { If Guice is asked to create an instance of CheckoutPanel, it will invoke this constructor and provide an instance of BookInventory and CreditCardService Your code doesn t need to create the dependencies any can also be applied to methods and non-final instance fields methods that are invoked by methods are invoked by Guice after the instance is created Guice automatically injects a Logger whose name is the name of the class into which it is injected. And you can t change it. 21

22 Guice Modules A Guice module tells the Guice infrastructure about well-known objects Your modules subclass com.google.inject.abstractmodule Objects are bound into Guice using the bind method Linking a type to its implementation (like a factory method) bind(bookinventory.class).to(bookdatabase.class); Whenever an object depends on a BookInventory, Guice will provide it with an instance of BookDatabase By default, Guice will create a new instance of a bound class when it is requested Singleton objects in Guice can be configured in two ways Annotating the object s class Binding the type in the singleton scope bind(creditcardservice.class).to(firstbankofpsu.class).in(singleton.class); 22

23 Annotations for Binding annotation can be used to name well-known objects From public String int serverport ) In your module, you can bind the values of the named objects: bind(string.class).annotatedwith(names.named("serverhost")).toinstance("localhost"); bind(integer.class).annotatedwith(names.named("serverport")).toinstance( 8080 ); When Guice instantiates FirstBankOfPSU it will provide the values of the server host and port. 23

24 Annotations for Binding You can also create your own annotation types for well-known objects DataDirectory is an annotation for the directory in which application data is stored package edu.pdx.cs410j.di; import com.google.inject.bindingannotation; @Target({ElementType.PARAMETER, DataDirectory means that the annotation being defined can be used with Guice 24

25 Annotations for Binding You can annotate constructor public File directory) And bind the value in your module: String tmpdir = System.getProperty("java.io.tmpdir"); File directory = new File(tmpdir); bind(file.class).annotatedwith(datadirectory.class).toinstance(directory); 25

26 Creating an Injector A Guice module is used to create an Injector which provides access to well-known objects public class GuicyBookStoreApp extends BookStoreApp { public static void main(string... args) { Injector injector = Guice.createInjector(new BookStoreModule()); BookInventory inventory = injector.getinstance(bookinventory.class); addbooks(inventory); BookStoreGUI gui = injector.getinstance(bookstoregui.class); gui.pack(); gui.setvisible(true); Guice takes care of creating and configuring all of the dependencies of BookStoreGUI and wiring them together Ultimately, your code is more decoupled and can be reconfigured more easily 26

27 Provider Methods Sometimes, objects need more than a constructor call in order to be initialized Or the constructor needs dependencies that are not provided by Guice A module method that is annotated constructs a Guice-managed instance of its return type This is probably a better way to configure the protected File providedatadirectory() { String tmpdir = System.getProperty("java.io.tmpdir"); return new File(tmpdir); It would probably be better to construct the FirstBankOfPSU using a provider method, also. You wouldn t need constructor parameters that reused anywhere 27

28 Provider classes A Provider class is used to create very expensive objects or objects that you want lazily initialize public class EncyrptionKeyProvider implements Provider<EncryptionKey> { private final EncryptionAlgorithm public EncyrptionKeyProvider(EncryptionAlgorithm al this.algorithm = public EncyrptionKey get() { // Perform expensive operation on demand return new EncryptionKey(algorithm); Bind with: bind(encyrptionkey.class).toprovider(encyrptionkeyprovider.class); 28

29 Provider classes Guice can inject a provider into an public class ConnectionManager private Provider<EncryptionKey> keyprovider; public ConnectionManager() { // Should inject Provider as parameter instead public Connection createconnection() { return new Connection(keyProvider.get()); Even though the ConnectionManager is a singleton, it can get multiple EncyrptionKeys by injecting the Provider Okay, ConnectionManager is a factory and we could probably doing this Guicier, but you get the point 29

30 Summary Dependency Injection is the ultimate expression of programming to the interface The Hollywood Principle states that objects should receive their dependencies upon construction When dependencies are decoupled, finer-grained testing is possible Mockito provides facilities for mocking objects and specifying mocked behavior Google Guice manages dependencies by separating configuration code from application code 30

Big Modular Java with Guice

Big Modular Java with Guice Big Modular Java with Guice Jesse Wilson Dhanji Prasanna May 28, 2009 Post your questions for this talk on Google Moderator: code.google.com/events/io/questions Click on the Tech Talks Q&A link. 2 How

More information

Dependency Injection with Guice

Dependency Injection with Guice Author: Assaf Israel - Technion 2013 Dependency Injection with Guice Technion Institute of Technology 236700 1 Complex Dependency Injection Deep dependencies (with no default) A depends on B, which depends

More information

The Singleton Pattern. Design Patterns In Java Bob Tarr

The Singleton Pattern. Design Patterns In Java Bob Tarr The Singleton Pattern Intent Ensure a class only has one instance, and provide a global point of access to it Motivation Sometimes we want just a single instance of a class to exist in the system For example,

More information

Thinking Functionally

Thinking Functionally Thinking Functionally Dan S. Wallach and Mack Joyner, Rice University Copyright 2016 Dan S. Wallach, All Rights Reserved Reminder: Fill out our web form! Fill this out ASAP if you haven t already. http://goo.gl/forms/arykwbc0zy

More information

Dependency Injection & Design Principles Recap Reid Holmes

Dependency Injection & Design Principles Recap Reid Holmes Material and some slide content from: - Krzysztof Czarnecki - Ian Sommerville - Head First Design Patterns Dependency Injection & Design Principles Recap Reid Holmes REID HOLMES - SE2: SOFTWARE DESIGN

More information

Test Isolation and Mocking

Test Isolation and Mocking Test Isolation and Mocking Technion Institute of Technology 236700 1 Author: Assaf Israel Unit Testing: Isolation The bigger the test subject the harder it is to understand the reason of a bug from a test

More information

Pieter van den Hombergh Stefan Sobek. April 18, 2018

Pieter van den Hombergh Stefan Sobek. April 18, 2018 Pieter van den Hombergh Stefan Sobek Fontys Hogeschool voor Techniek en Logistiek April 18, 2018 /FHTenL April 18, 2018 1/13 To mock or not to mock In many cases, a class (system under test or SUT) does

More information

Guice. Java DI Framework

Guice. Java DI Framework Guice Java DI Framework Agenda Intro to dependency injection Cross-cutting concerns and aspectoriented programming More Guice What is DI? Dependency injection is a design pattern that's like a "super factory".

More information

Unit Tes2ng Ac2vity. SWEN-261 Introduc2on to So3ware Engineering. Department of So3ware Engineering Rochester Ins2tute of Technology

Unit Tes2ng Ac2vity. SWEN-261 Introduc2on to So3ware Engineering. Department of So3ware Engineering Rochester Ins2tute of Technology Unit Tes2ng Ac2vity SWEN-261 Introduc2on to So3ware Engineering Department of So3ware Engineering Rochester Ins2tute of Technology Your activity for the Unit Testing lesson is to build tests for existing

More information

Topics covered. Introduction to JUnit JUnit: Hands-on session Introduction to Mockito Mockito: Hands-on session. JUnit & Mockito 2

Topics covered. Introduction to JUnit JUnit: Hands-on session Introduction to Mockito Mockito: Hands-on session. JUnit & Mockito 2 JUnit & Mockito 1 Topics covered Introduction to JUnit JUnit: Hands-on session Introduction to Mockito Mockito: Hands-on session JUnit & Mockito 2 Introduction to JUnit JUnit & Mockito 3 What is JUnit?

More information

Dependency Injection & Design Principles Recap Reid Holmes

Dependency Injection & Design Principles Recap Reid Holmes Material and some slide content from: - Krzysztof Czarnecki - Ian Sommerville - Head First Design Patterns Dependency Injection & Design Principles Recap Reid Holmes REID HOLMES - SE2: SOFTWARE DESIGN

More information

Class, Variable, Constructor, Object, Method Questions

Class, Variable, Constructor, Object, Method Questions Class, Variable, Constructor, Object, Method Questions http://www.wideskills.com/java-interview-questions/java-classes-andobjects-interview-questions https://www.careerride.com/java-objects-classes-methods.aspx

More information

Design Patterns. Dependency Injection. Oliver Haase

Design Patterns. Dependency Injection. Oliver Haase Design Patterns Dependency Injection Oliver Haase 1 Motivation A simple, motivating example (by Martin Fowler): public interface MovieFinder { /** * returns all movies of this finder s source * @return

More information

Introduction to Software Engineering: Tools and Environments. Session 5. Oded Lachish

Introduction to Software Engineering: Tools and Environments. Session 5. Oded Lachish Introduction to Software Engineering: Tools and Environments Session 5 Oded Lachish Room: Mal 405 Visiting Hours: Wednesday 17:00 to 20:00 Email: oded@dcs.bbk.ac.uk Module URL: http://www.dcs.bbk.ac.uk/~oded/tools2012-2013/web/tools2012-2013.html

More information

School of Informatics, University of Edinburgh

School of Informatics, University of Edinburgh CS1Bh Solution Sheet 4 Software Engineering in Java This is a solution set for CS1Bh Question Sheet 4. You should only consult these solutions after attempting the exercises. Notice that the solutions

More information

The compilation process is driven by the syntactic structure of the program as discovered by the parser

The compilation process is driven by the syntactic structure of the program as discovered by the parser Semantic Analysis The compilation process is driven by the syntactic structure of the program as discovered by the parser Semantic routines: interpret meaning of the program based on its syntactic structure

More information

interface MyAnno interface str( ) val( )

interface MyAnno interface str( ) val( ) Unit 4 Annotations: basics of annotation-the Annotated element Interface. Using Default Values, Marker Annotations. Single-Member Annotations. The Built-In Annotations-Some Restrictions. 1 annotation Since

More information

The Singleton Pattern. Design Patterns In Java Bob Tarr

The Singleton Pattern. Design Patterns In Java Bob Tarr The Singleton Pattern Intent Ensure a class only has one instance, and provide a global point of access to it Motivation Sometimes we want just a single instance of a class to exist in the system For example,

More information

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

Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L Inheritance Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 9.4 1 Inheritance Inheritance allows a software developer to derive

More information

Abstract. 1. What is an ABSTRACT METHOD? 2. Why you would want to declare a method as abstract? 3. A non-abstract CLASS is called a concrete class

Abstract. 1. What is an ABSTRACT METHOD? 2. Why you would want to declare a method as abstract? 3. A non-abstract CLASS is called a concrete class ABSTRACT 2 1. What is an ABSTRACT METHOD? 2 2. Why you would want to declare a method as abstract? 2 3. A non-abstract CLASS is called a concrete class 2 4. Abstract Example 2 5. If you are extending ABSTRACT

More information

Testing on Android. Mobile Application Development. Jakob Mass MTAT Fall MTAT

Testing on Android. Mobile Application Development. Jakob Mass MTAT Fall MTAT Testing on Android Mobile Application Development MTAT.03.262 2017 Fall Jakob Mass jakob.mass@ut.ee Introduction. Perfect codewriting...or? Conventional (unit) Java testing with JUnit How is mobile/android

More information

Unit Testing Activity

Unit Testing Activity Unit Testing Activity SWEN-261 Introduction to Software Engineering Department of Software Engineering Rochester Institute of Technology Your activity for the Unit Testing lesson is to build tests for

More information

Binghamton University. CS-140 Fall Problem Solving. Creating a class from scratch

Binghamton University. CS-140 Fall Problem Solving. Creating a class from scratch Problem Solving Creating a class from scratch 1 Recipe for Writing a Class 1. Write the class boilerplate stuff 2. Declare Fields 3. Write Creator(s) 4. Write accessor methods 5. Write mutator methods

More information

Classes, interfaces, & documentation. Review of basic building blocks

Classes, interfaces, & documentation. Review of basic building blocks Classes, interfaces, & documentation Review of basic building blocks Objects Data structures literally, storage containers for data constitute object knowledge or state Operations an object can perform

More information

Logistics. Final Exam on Friday at 3pm in CHEM 102

Logistics. Final Exam on Friday at 3pm in CHEM 102 Java Review Logistics Final Exam on Friday at 3pm in CHEM 102 What is a class? A class is primarily a description of objects, or instances, of that class A class contains one or more constructors to create

More information

Project #1 rev 2 Computer Science 2334 Fall 2013 This project is individual work. Each student must complete this assignment independently.

Project #1 rev 2 Computer Science 2334 Fall 2013 This project is individual work. Each student must complete this assignment independently. Project #1 rev 2 Computer Science 2334 Fall 2013 This project is individual work. Each student must complete this assignment independently. User Request: Create a simple magazine data system. Milestones:

More information

CS 330 Homework Comma-Separated Expression

CS 330 Homework Comma-Separated Expression CS 330 Homework Comma-Separated Expression 1 Overview Your responsibility in this homework is to build an interpreter for text-based spreadsheets, which are essentially CSV files with formulas or expressions

More information

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

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring Java Outline Java Models for variables Types and type checking, type safety Interpretation vs. compilation Reasoning about code CSCI 2600 Spring 2017 2 Java Java is a successor to a number of languages,

More information

Outline. 15. Inheritance. Programming in Java. Computer Science Dept Va Tech August D Barnette, B Keller & P Schoenhoff

Outline. 15. Inheritance. Programming in Java. Computer Science Dept Va Tech August D Barnette, B Keller & P Schoenhoff Outline 1 Inheritance: extends ; Superclasses and Subclasses Valid and invalid object states, & Instance variables: protected Inheritance and constructors, super The is-a vs. has-a relationship (Inheritance

More information

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

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University Day 4 COMP1006/1406 Summer 2016 M. Jason Hinek Carleton University today s agenda assignments questions about assignment 2 a quick look back constructors signatures and overloading encapsulation / information

More information

Rules and syntax for inheritance. The boring stuff

Rules and syntax for inheritance. The boring stuff Rules and syntax for inheritance The boring stuff The compiler adds a call to super() Unless you explicitly call the constructor of the superclass, using super(), the compiler will add such a call for

More information

1 Shyam sir JAVA Notes

1 Shyam sir JAVA Notes 1 Shyam sir JAVA Notes 1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write

More information

The Object clone() Method

The Object clone() Method The Object clone() Method Introduction In this article from my free Java 8 course, I will be discussing the Java Object clone() method. The clone() method is defined in class Object which is the superclass

More information

CS211 Computers and Programming Matthew Harris and Alexa Sharp July 9, Boggle

CS211 Computers and Programming Matthew Harris and Alexa Sharp July 9, Boggle Boggle If you are not familiar with the game Boggle, the game is played with 16 dice that have letters on all faces. The dice are randomly deposited into a four-by-four grid so that the players see the

More information

mvn package -Dmaven.test.skip=false //builds DSpace and runs tests

mvn package -Dmaven.test.skip=false //builds DSpace and runs tests DSpace Testing 1 Introduction 2 Quick Start 2.1 Maven 2.2 JUnit 2.3 JMockit 2.4 ContiPerf 2.5 H2 3 Unit Tests Implementation 3.1 Structure 3.2 Limitations 3.3 How to build new tests 3.4 How to run the

More information

Basic Keywords Practice Session

Basic Keywords Practice Session Basic Keywords Practice Session Introduction In this article from my free Java 8 course, we will apply what we learned in my Java 8 Course Introduction to our first real Java program. If you haven t yet,

More information

After completing Matchers, you will be able to: Describe the advantages of encapsulating verification logic in

After completing Matchers, you will be able to: Describe the advantages of encapsulating verification logic in CHAPTER 3 MATCHERS OBJECTIVES After completing Matchers, you will be able to: Describe the advantages of encapsulating verification logic in matchers. Use built-in matchers from the Hamcrest library. Create

More information

Design patterns using Spring and Guice

Design patterns using Spring and Guice Design patterns using Spring and Guice Dhanji R. Prasanna MANNING contents 1 Dependency 2 Time preface xv acknowledgments xvii about this book xix about the cover illustration xxii injection: what s all

More information

Inheritance. Transitivity

Inheritance. Transitivity Inheritance Classes can be organized in a hierarchical structure based on the concept of inheritance Inheritance The property that instances of a sub-class can access both data and behavior associated

More information

CMPSCI 187: Programming With Data Structures. Lecture 6: The StringLog ADT David Mix Barrington 17 September 2012

CMPSCI 187: Programming With Data Structures. Lecture 6: The StringLog ADT David Mix Barrington 17 September 2012 CMPSCI 187: Programming With Data Structures Lecture 6: The StringLog ADT David Mix Barrington 17 September 2012 The StringLog ADT Data Abstraction Three Views of Data Java Interfaces Defining the StringLog

More information

COP 3330 Final Exam Review

COP 3330 Final Exam Review COP 3330 Final Exam Review I. The Basics (Chapters 2, 5, 6) a. comments b. identifiers, reserved words c. white space d. compilers vs. interpreters e. syntax, semantics f. errors i. syntax ii. run-time

More information

JSR-305: Annotations for Software Defect Detection

JSR-305: Annotations for Software Defect Detection JSR-305: Annotations for Software Defect Detection William Pugh Professor Univ. of Maryland pugh@cs.umd.edu http://www.cs.umd.edu/~pugh/ 1 Why annotations? Static analysis can do a lot can even analyze

More information

CS 61B Data Structures and Programming Methodology. July 7, 2008 David Sun

CS 61B Data Structures and Programming Methodology. July 7, 2008 David Sun CS 61B Data Structures and Programming Methodology July 7, 2008 David Sun Announcements You ve started (or finished) project 1, right? Package Visibility public declarations represent specifications what

More information

Import Statements, Instance Members, and the Default Constructor

Import Statements, Instance Members, and the Default Constructor Import Statements, Instance Members, and the Default Constructor Introduction In this article from my free Java 8 course, I will be discussing import statements, instance members, and the default constructor.

More information

Project 1 Computer Science 2334 Spring 2016 This project is individual work. Each student must complete this assignment independently.

Project 1 Computer Science 2334 Spring 2016 This project is individual work. Each student must complete this assignment independently. Project 1 Computer Science 2334 Spring 2016 This project is individual work. Each student must complete this assignment independently. User Request: Create a simple movie data system. Milestones: 1. Use

More information

Errors and Exceptions

Errors and Exceptions Exceptions Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null reference An exception isn t necessarily your fault trying

More information

Unit Testing & Testability

Unit Testing & Testability CMPT 473 Software Quality Assurance Unit Testing & Testability Nick Sumner - Fall 2014 Levels of Testing Recall that we discussed different levels of testing for test planning: Unit Tests Integration Tests

More information

Polymorphic Associations Library

Polymorphic Associations Library Polymorphic Associations Library Table of Contents Rationale.................................................................................. 2 Table of Two Halves Pattern...............................................................

More information

CSE 70 Final Exam Fall 2009

CSE 70 Final Exam Fall 2009 Signature cs70f Name Student ID CSE 70 Final Exam Fall 2009 Page 1 (10 points) Page 2 (16 points) Page 3 (22 points) Page 4 (13 points) Page 5 (15 points) Page 6 (20 points) Page 7 (9 points) Page 8 (15

More information

Written by John Bell for CS 342, Spring 2018

Written by John Bell for CS 342, Spring 2018 Advanced OO Concepts Written by John Bell for CS 342, Spring 2018 Based on chapter 3 of The Object-Oriented Thought Process by Matt Weisfeld, with additional material from other sources. Constructors Constructors

More information

Checked and Unchecked Exceptions in Java

Checked and Unchecked Exceptions in Java Checked and Unchecked Exceptions in Java Introduction In this article from my free Java 8 course, I will introduce you to Checked and Unchecked Exceptions in Java. Handling exceptions is the process by

More information

Building custom components IAT351

Building custom components IAT351 Building custom components IAT351 Week 1 Lecture 1 9.05.2012 Lyn Bartram lyn@sfu.ca Today Review assignment issues New submission method Object oriented design How to extend Java and how to scope Final

More information

Accessibility. Adding features to support users with impaired vision, mobility, or hearing

Accessibility. Adding features to support users with impaired vision, mobility, or hearing Accessibility Adding features to support users with impaired vision, mobility, or hearing TalkBack TalkBack is an Android screen reader made by Google. It speaks out the contents of a screen based on what

More information

Chapter 14 Abstract Classes and Interfaces

Chapter 14 Abstract Classes and Interfaces Chapter 14 Abstract Classes and Interfaces 1 What is abstract class? Abstract class is just like other class, but it marks with abstract keyword. In abstract class, methods that we want to be overridden

More information

Subclassing for ADTs Implementation

Subclassing for ADTs Implementation Object-Oriented Design Lecture 8 CS 3500 Fall 2009 (Pucella) Tuesday, Oct 6, 2009 Subclassing for ADTs Implementation An interesting use of subclassing is to implement some forms of ADTs more cleanly,

More information

Introduction to Object-Oriented Programming

Introduction to Object-Oriented Programming Polymorphism 1 / 19 Introduction to Object-Oriented Programming Today we ll learn how to combine all the elements of object-oriented programming in the design of a program that handles a company payroll.

More information

ArrayList. Introduction. java.util.arraylist

ArrayList. Introduction. java.util.arraylist ArrayList Introduction In this article from my free Java 8 course, I will be giving you a basic overview of the Java class java.util.arraylist. I will first explain the meaning of size and capacity of

More information

C++ without Classes. CMSC433, Fall 2001 Programming Language Technology and Paradigms. More C++ without Classes. Project 1. new/delete.

C++ without Classes. CMSC433, Fall 2001 Programming Language Technology and Paradigms. More C++ without Classes. Project 1. new/delete. CMSC433, Fall 2001 Programming Language Technology and Paradigms Adam Porter Sept. 4, 2001 C++ without Classes Don t need to say struct New libraries function overloading confusing link messages default

More information

Answer Key. 1. General Understanding (10 points) think before you decide.

Answer Key. 1. General Understanding (10 points) think before you decide. Answer Key 1. General Understanding (10 points) Answer the following questions with yes or no. think before you decide. Read the questions carefully and (a) (2 points) Does the interface java.util.sortedset

More information

UMBC CMSC 331 Final Exam

UMBC CMSC 331 Final Exam UMBC CMSC 331 Final Exam Name: UMBC Username: You have two hours to complete this closed book exam. We reserve the right to assign partial credit, and to deduct points for answers that are needlessly wordy

More information

Example: Count of Points

Example: Count of Points Example: Count of Points 1 public class Point { 2... 3 private static int numofpoints = 0; 4 5 public Point() { 6 numofpoints++; 7 } 8 9 public Point(int x, int y) { 10 this(); // calling Line 5 11 this.x

More information

Comparing Spring & Guice

Comparing Spring & Guice Comparing Spring & Guice Bill Dudney Dudney.net Bill Dudney Comparing Spring & Guice Slide 1 Dependency Injection WarpSimulator capacitor : FluxCapacitor simulate() : void FluxCapacitor capacitate()

More information

Chapter 5. Inheritance

Chapter 5. Inheritance Chapter 5 Inheritance Objectives Know the difference between Inheritance and aggregation Understand how inheritance is done in Java Learn polymorphism through Method Overriding Learn the keywords : super

More information

Example: Count of Points

Example: Count of Points Example: Count of Points 1 class Point { 2... 3 private static int numofpoints = 0; 4 5 Point() { 6 numofpoints++; 7 } 8 9 Point(int x, int y) { 10 this(); // calling the constructor with no input argument;

More information

Assignment 5: Design Patterns

Assignment 5: Design Patterns Assignment 5: Design Patterns Exercise 1 Examine the listed Java APIs (see e.g. https://docs.oracle.com/javase/7/docs/api/ for more information) and identify some of the design patterns present. For each

More information

Declarations and Access Control SCJP tips

Declarations and Access Control  SCJP tips Declarations and Access Control www.techfaq360.com SCJP tips Write code that declares, constructs, and initializes arrays of any base type using any of the permitted forms both for declaration and for

More information

PRINCIPLES OF SOFTWARE BIM209DESIGN AND DEVELOPMENT 00. WELCOME TO OBJECTVILLE. Speaking the Language of OO

PRINCIPLES OF SOFTWARE BIM209DESIGN AND DEVELOPMENT 00. WELCOME TO OBJECTVILLE. Speaking the Language of OO PRINCIPLES OF SOFTWARE BIM209DESIGN AND DEVELOPMENT 00. WELCOME TO OBJECTVILLE Speaking the Language of OO COURSE INFO Instructor : Alper Bilge TA : Gökhan Çıplak-Ahmet Alkılınç Time : Tuesdays 2-5pm Location

More information

Instance Members and Static Members

Instance Members and Static Members Instance Members and Static Members You may notice that all the members are declared w/o static. These members belong to some specific object. They are called instance members. This implies that these

More information

CSE wi Final Exam 3/12/18. Name UW ID#

CSE wi Final Exam 3/12/18. Name UW ID# Name UW ID# There are 13 questions worth a total of 100 points. Please budget your time so you get to all of the questions. Keep your answers brief and to the point. The exam is closed book, closed notes,

More information

Comp 249 Programming Methodology Chapter 9 Exception Handling

Comp 249 Programming Methodology Chapter 9 Exception Handling Comp 249 Programming Methodology Chapter 9 Exception Handling Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal, Canada These slides has been extracted,

More information

Chapter 9. Exception Handling. Copyright 2016 Pearson Inc. All rights reserved.

Chapter 9. Exception Handling. Copyright 2016 Pearson Inc. All rights reserved. Chapter 9 Exception Handling Copyright 2016 Pearson Inc. All rights reserved. Last modified 2015-10-02 by C Hoang 9-2 Introduction to Exception Handling Sometimes the best outcome can be when nothing unusual

More information

Binghamton University. CS-140 Fall Functional Java

Binghamton University. CS-140 Fall Functional Java Functional Java 1 First Class Data We have learned how to manipulate data with programs We can pass data to methods via arguments We can return data from methods via return types We can encapsulate data

More information

CS 61B Discussion 5: Inheritance II Fall 2014

CS 61B Discussion 5: Inheritance II Fall 2014 CS 61B Discussion 5: Inheritance II Fall 2014 1 WeirdList Below is a partial solution to the WeirdList problem from homework 3 showing only the most important lines. Part A. Complete the implementation

More information

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS PAUL L. BAILEY Abstract. This documents amalgamates various descriptions found on the internet, mostly from Oracle or Wikipedia. Very little of this

More information

Project Lambda in Java SE 8

Project Lambda in Java SE 8 Project Lambda in Java SE 8 Daniel Smith Java Language Designer 1 The following is intended to outline our general product direction. It is intended for information purposes only, and may not be incorporated

More information

Patterns Continued and Concluded. July 26, 2017

Patterns Continued and Concluded. July 26, 2017 Patterns Continued and Concluded July 26, 2017 Review Quiz What is the purpose of the Singleton pattern? A. To advertise to other developers that the object should only be modified by `main()` B.To prevent

More information

Object-Oriented Concepts

Object-Oriented Concepts JAC444 - Lecture 3 Object-Oriented Concepts Segment 2 Inheritance 1 Classes Segment 2 Inheritance In this segment you will be learning about: Inheritance Overriding Final Methods and Classes Implementing

More information

Homework 6. Yuji Shimojo CMSC 330. Instructor: Prof. Reginald Y. Haseltine

Homework 6. Yuji Shimojo CMSC 330. Instructor: Prof. Reginald Y. Haseltine Homework 6 Yuji Shimojo CMSC 330 Instructor: Prof. Reginald Y. Haseltine July 21, 2013 Question 1 What is the output of the following C++ program? #include #include using namespace

More information

Software Paradigms (Lesson 3) Object-Oriented Paradigm (2)

Software Paradigms (Lesson 3) Object-Oriented Paradigm (2) Software Paradigms (Lesson 3) Object-Oriented Paradigm (2) Table of Contents 1 Reusing Classes... 2 1.1 Composition... 2 1.2 Inheritance... 4 1.2.1 Extending Classes... 5 1.2.2 Method Overriding... 7 1.2.3

More information

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS Chapter 1 : Chapter-wise Java Multiple Choice Questions and Answers Interview MCQs Java Programming questions and answers with explanation for interview, competitive examination and entrance test. Fully

More information

Exceptions. Errors and Exceptions. Dealing with exceptions. What to do about errors and exceptions

Exceptions. Errors and Exceptions. Dealing with exceptions. What to do about errors and exceptions Errors and Exceptions Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null reference An exception is a problem whose cause is outside

More information

More Relationships Between Classes

More Relationships Between Classes More Relationships Between Classes Inheritance: passing down states and behaviors from the parents to their children Interfaces: grouping the methods, which belongs to some classes, as an interface to

More information

CMSC 433 Programming Language Technologies and Paradigms. Spring 2013

CMSC 433 Programming Language Technologies and Paradigms. Spring 2013 CMSC 433 Programming Language Technologies and Paradigms Spring 2013 Encapsulation, Publication, Escape Data Encapsulation One of the approaches in object-oriented programming is to use data encapsulation

More information

Dealing with Bugs. Kenneth M. Anderson University of Colorado, Boulder CSCI 5828 Lecture 27 04/21/2009

Dealing with Bugs. Kenneth M. Anderson University of Colorado, Boulder CSCI 5828 Lecture 27 04/21/2009 Dealing with Bugs Kenneth M. Anderson University of Colorado, Boulder CSCI 5828 Lecture 27 04/21/2009 University of Colorado, 2009 1 Goals 2 Review material from Chapter 11 of Pilone & Miles Dealing with

More information

COMP 110/L Lecture 6. Kyle Dewey

COMP 110/L Lecture 6. Kyle Dewey COMP 110/L Lecture 6 Kyle Dewey Outline Methods Variable scope Call-by-value Testing with JUnit Variable Scope Question Does this compile? public class Test { public static void main(string[] args) { int

More information

DESIGN PATTERN - INTERVIEW QUESTIONS

DESIGN PATTERN - INTERVIEW QUESTIONS DESIGN PATTERN - INTERVIEW QUESTIONS http://www.tutorialspoint.com/design_pattern/design_pattern_interview_questions.htm Copyright tutorialspoint.com Dear readers, these Design Pattern Interview Questions

More information

Lab 5: Java IO 12:00 PM, Feb 21, 2018

Lab 5: Java IO 12:00 PM, Feb 21, 2018 CS18 Integrated Introduction to Computer Science Fisler, Nelson Contents Lab 5: Java IO 12:00 PM, Feb 21, 2018 1 The Java IO Library 1 2 Program Arguments 2 3 Readers, Writers, and Buffers 2 3.1 Buffering

More information

Note that this is essentially the same UML as the State pattern! The intent of each of the two patterns is quite different however:

Note that this is essentially the same UML as the State pattern! The intent of each of the two patterns is quite different however: Note that this is essentially the same UML as the State pattern! The intent of each of the two patterns is quite different however: State is about encapsulating behaviour that is linked to specific internal

More information

About This Lecture. Data Abstraction - Interfaces and Implementations. Outline. Object Concepts. Object Class, Protocol and State.

About This Lecture. Data Abstraction - Interfaces and Implementations. Outline. Object Concepts. Object Class, Protocol and State. Revised 01/09/05 About This Lecture Slide # 2 Data Abstraction - Interfaces and Implementations In this lecture we will learn how Java objects and classes can be used to build abstract data types. CMPUT

More information

COE318 Lecture Notes Week 9 (Week of Oct 29, 2012)

COE318 Lecture Notes Week 9 (Week of Oct 29, 2012) COE318 Lecture Notes: Week 9 1 of 14 COE318 Lecture Notes Week 9 (Week of Oct 29, 2012) Topics The final keyword Inheritance and Polymorphism The final keyword Zoo: Version 1 This simple version models

More information

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

CSCI-142 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community CSCI-12 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community http://csc.cs.rit.edu 1. Provide a detailed explanation of what the following code does: 1 public boolean checkstring

More information

CSE331 Winter 2014, Final Examination March 17, 2014 Please do not turn the page until 8:30. Rules:

CSE331 Winter 2014, Final Examination March 17, 2014 Please do not turn the page until 8:30. Rules: CSE331 Winter 2014, Final Examination March 17, 2014 Please do not turn the page until 8:30. Rules: The exam is closed-book, closed-note, etc. Please stop promptly at 10:20. There are 116 points total,

More information

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

Overview. Lecture 7: Inheritance and GUIs. Inheritance. Example 9/30/2008 Overview Lecture 7: Inheritance and GUIs Written by: Daniel Dalevi Inheritance Subclasses and superclasses Java keywords Interfaces and inheritance The JComponent class Casting The cosmic superclass Object

More information

Mock Objects and the Mockito Testing Framework Carl Veazey CSCI Friday, March 23, 12

Mock Objects and the Mockito Testing Framework Carl Veazey CSCI Friday, March 23, 12 Mock Objects and the Mockito Testing Framework Carl Veazey CSCI 5828 Introduction Mock objects are a powerful testing pattern for verifying the behavior and interactions of systems. This presentation aims

More information

Soda Machine Laboratory

Soda Machine Laboratory Soda Machine Laboratory Introduction This laboratory is intended to give you experience working with multiple queue structures in a familiar real-world setting. The given application models a soda machine

More information

Utilities (Part 2) Implementing static features

Utilities (Part 2) Implementing static features Utilities (Part 2) Implementing static features 1 Goals for Today learn about preventing class instantiation learn about methods static methods method header method signature method return type method

More information

COE318 Lecture Notes Week 8 (Oct 24, 2011)

COE318 Lecture Notes Week 8 (Oct 24, 2011) COE318 Software Systems Lecture Notes: Week 8 1 of 17 COE318 Lecture Notes Week 8 (Oct 24, 2011) Topics == vs..equals(...): A first look Casting Inheritance, interfaces, etc Introduction to Juni (unit

More information

Inheritance. Benefits of Java s Inheritance. 1. Reusability of code 2. Code Sharing 3. Consistency in using an interface. Classes

Inheritance. Benefits of Java s Inheritance. 1. Reusability of code 2. Code Sharing 3. Consistency in using an interface. Classes Inheritance Inheritance is the mechanism of deriving new class from old one, old class is knows as superclass and new class is known as subclass. The subclass inherits all of its instances variables and

More information

Exceptions. Examples of code which shows the syntax and all that

Exceptions. Examples of code which shows the syntax and all that Exceptions Examples of code which shows the syntax and all that When a method might cause a checked exception So the main difference between checked and unchecked exceptions was that the compiler forces

More information

Design Patterns: State, Bridge, Visitor

Design Patterns: State, Bridge, Visitor Design Patterns: State, Bridge, Visitor State We ve been talking about bad uses of case statements in programs. What is one example? Another way in which case statements are sometimes used is to implement

More information