CSCE 156 Computer Science II

Similar documents
CSCE 156 Computer Science II

CSCE Java. Dr. Chris Bourke. Prior to Lab. Peer Programming Pair-Up. Lab 15 - Databases & Java Database Connectivity API

CSCE Java. Lab 13 - Searching & Sorting. Dr. Chris Bourke

CSCE 156 Computer Science II

CSCE C. Lab 10 - File I/O. Dr. Chris Bourke

COMP 250 Winter 2011 Reading: Java background January 5, 2011

ENCAPSULATION. private, public, scope and visibility rules. packages and package level access.

CmSc 150 Fundamentals of Computing I. Lesson 28: Introduction to Classes and Objects in Java. 1. Classes and Objects

Programming II (CS300)

Encapsulation. Administrative Stuff. September 12, Writing Classes. Quick review of last lecture. Classes. Classes and Objects

Chapter 4 Defining Classes I

Encapsulation. Mason Vail Boise State University Computer Science

CS112 Lecture: Defining Instantiable Classes

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

Anatomy of a Method. HW3 is due Today. September 15, Midterm 1. Quick review of last lecture. Encapsulation. Encapsulation

Data Structures (list, dictionary, tuples, sets, strings)

Objects and Classes. 1 Creating Classes and Objects. CSCI-UA 101 Objects and Classes

ECE 122. Engineering Problem Solving with Java

Chapter 4: Writing Classes

This course supports the assessment for Scripting and Programming Applications. The course covers 4 competencies and represents 4 competency units.

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

Programming Exercise 14: Inheritance and Polymorphism

CS1004: Intro to CS in Java, Spring 2005

Programming II (CS300)

Principles of Object Oriented Programming. Lecture 4

Object Oriented Programming

CS111: PROGRAMMING LANGUAGE II. Lecture 1: Introduction to classes

Al al-bayt University Prince Hussein Bin Abdullah College for Information Technology Computer Science Department

COP 3330 Final Exam Review

Programming for Engineers in Python

Classes Classes 2 / 36

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and More

Classes Classes 2 / 35

CLASSES AND OBJECTS IN JAVA

Object Oriented Programming. Week 1 Part 1 An introduction to Java, Objects and JUnit

Comments are almost like C++

COMSC-051 Java Programming Part 1. Part-Time Instructor: Joenil Mistal

G52CPP C++ Programming Lecture 9

Methods and Data (Savitch, Chapter 5)

An Introduction to C++

Chapter 13. Interfaces and Inner Classes

Java OOP: Java Documentation

5. Defining Classes and Methods

CSCI 1301: Introduction to Computing and Programming Summer 2018 Lab 07 Classes and Methods

(5 2) Introduction to Classes in C++ Instructor - Andrew S. O Fallon CptS 122 (February 7, 2018) Washington State University

CSCE 120: Learning To Code

Overview of Eclipse Lectures. Module Road Map

Software and Programming 1

Programming II (CS300)

Classes and Methods גרא וייס המחלקה למדעי המחשב אוניברסיטת בן-גוריון

CIS 110: Introduction to Computer Programming

Outline. CIS 110: Introduction to Computer Programming. Any questions? My life story. A horrible incident. The awful truth

EECS168 Exam 3 Review

Programming II (CS300)

CS1150 Principles of Computer Science Objects and Classes

A - 1. CS 494 Object-Oriented Analysis & Design. UML Class Models. Overview. Class Model Perspectives (cont d) Developing Class Models

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

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

Classes and Methods לאוניד ברנבוים המחלקה למדעי המחשב אוניברסיטת בן-גוריון

class objects instances Fields Constructors Methods static

by Pearson Education, Inc. All Rights Reserved. 2

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017

CS 170 Java Programming 1. Week 15: Interfaces and Exceptions

Inf1-OP. Inf1-OP Exam Review. Timothy Hospedales, adapting earlier version by Perdita Stevens and Ewan Klein. March 20, School of Informatics

Inheritance and Interfaces

(800) Toll Free (804) Fax Introduction to Java and Enterprise Java using Eclipse IDE Duration: 5 days

Object-Oriented Programming

13. Java Classes. Educational Objectives. Classes - Technical. Definition: Classes

Productivity! Feature Matrix

Understanding Inheritance and Interfaces

I Wish I Knew How To. Begin Object Oriented Programming With Xojo. By Eugene Dakin. July 2015 Edition (1.0)

Classes and Methods עזאם מרעי המחלקה למדעי המחשב אוניברסיטת בן-גוריון מבוסס על השקפים של אותו קורס שניתן בשנים הקודמות

Outline. Computer Science 331. Information Hiding. What This Lecture is About. Data Structures, Abstract Data Types, and Their Implementations

Project 1. Java Control Structures 1/17/2014. Project 1 and Java Intro. Project 1 (2) To familiarize with

Ticket Machine Project(s)

A A B U n i v e r s i t y

administrivia today UML start design patterns Tuesday, September 28, 2010

UNDERSTANDING CLASS DEFINITIONS CITS1001

Software Development. Modular Design and Algorithm Analysis

Lesson 10B Class Design. By John B. Owen All rights reserved 2011, revised 2014

Object Orientation. A Crash Course Intro

Tutorials. Tutorial every Friday at 11:30 AM in Toldo 204 * discuss the next lab assignment

Understanding the Object Paradigm

Final Exam. Programming Assignment 3. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings

CSC-140 Assignment 6

PROGRAMMING III OOP. JAVA LANGUAGE COURSE

Midterms Save the Dates!

CPS122 Lecture: Defining a Class

CS1004: Intro to CS in Java, Spring 2005

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Nested Classes in Java. Slides by: Alon Mishne Edited by: Eran Gilad, Eyal Moscovici April 2013

Object Oriented Programming in C#

Object-Oriented Design (OOD) and C++

COMP Information Hiding and Encapsulation. Yi Hong June 03, 2015

Static, Final & Memory Management

CSCI 1301: Introduction to Computing and Programming Spring 2019 Lab 10 Classes and Methods

THE BCS PROFESSIONAL EXAMINATION BCS Level 5 Diploma in IT September 2017 EXAMINERS REPORT

Write the code to create an enhanced for loop that will go through every member of an ArrayList <String> myarray and print it out to the console.

Classes. Classes as Code Libraries. Classes as Data Structures. Classes/Objects/Interfaces (Savitch, Various Chapters)

Transcription:

CSCE 156 Computer Science II Lab 04 - Classes & Constructors Dr. Chris Bourke Prior to Lab 1. Review this laboratory handout prior to lab. 2. Read Object Creation tutorial: http://download.oracle.com/javase/tutorial/java/javaoo/objectcreation. html 3. Read constructor tutorial: http://download.oracle.com/javase/tutorial/java/javaoo/arguments.html Lab Objectives & Topics Following the lab, you should be able to: Use Classes and objects to write Java programs Understand and use constructors Understand the visibility of a class s methods and how to use them Peer Programming Pair-Up To encourage collaboration and a team environment, labs will be structured in a pair programming setup. At the start of each lab, you will be randomly paired up with another student (conflicts such as absences will be dealt with by the lab instructor). One of you will be designated the driver and the other the navigator. 1

The navigator will be responsible for reading the instructions and telling the driver what to do next. The driver will be in charge of the keyboard and workstation. Both driver and navigator are responsible for suggesting fixes and solutions together. Neither the navigator nor the driver is in charge. Beyond your immediate pairing, you are encouraged to help and interact and with other pairs in the lab. Each week you should alternate: if you were a driver last week, be a navigator next, etc. Resolve any issues (you were both drivers last week) within your pair. Ask the lab instructor to resolve issues only when you cannot come to a consensus. Because of the peer programming setup of labs, it is absolutely essential that you complete any pre-lab activities and familiarize yourself with the handouts prior to coming to lab. Failure to do so will negatively impact your ability to collaborate and work with others which may mean that you will not be able to complete the lab. Getting Started Clone the project code for this lab from GitHub in Eclipse using the URL, https: //github.com/cbourke/csce156-lab04-classesconstructors. Refer to Lab 01 for instructions on how to clone a project from GitHub. Classes & Constructors Java is a class-based Object Oriented Programming Language meaning that it realizes the concept of objects by allowing you to define classes which have member methods and variables. Instances of classes are instantiated through a constructor; a method with the same name as a class and called using the new keyword. This lab will familiarize you with how classes and their constructors are defined and used. In addition, you will be introduced to some ways that Java supports other Object Oriented Principles: Encapsulation and Abstraction. Encapsulation is the means by which objects group data and the methods/functions that act on that data. It is also the means by which a class s data is protected from the outside world (outside of the object). Java achieves this by allowing you to define member methods and variables and to specify the visibility of these fields (using the keywords private, protected, and public ). Abstraction refers to the means by which an object exposes a public interface to the outside world while hiding the inner workings (the internal representation or the implementation details). Java s main mechanism for supporting this is the same as with encapsulation though it does provide other means (interfaces, abstract classes). 2

Class Signaling refers to invoking methods on an instance of a class. Java uses the dot (or period) operator to signal a class. That is, to invoke one of its methods. Activities We have provided a Java project that simulates a library collections system. It has several classes already defined to model authors, books, a library (a collection of books) and a text-based interface which allows you to search the collection, add books to the collection, and list the collection. Constructing Constructors 1. Run the library program to familiarize yourself with its functionality. Note that printing the collection is not fully operational 2. Complete each of the accessor (getter) methods in the Book class. Best Practice Tip: always use the this keyword to disambiguate the scope of variables and prevent potential problems when subclassing. 3. Observe that the Book class does not have a constructor defined. Examine the addbook() code and determine how it is possible to create instances of the Book class without a constructor. 4. Modify the Book class by adding and implementing the following constructor. 1 public Book(String title, Author author, String isbn, 2 String publishdate) { 3 //TODO: your code here 4 } 5. Adding this constructor will cause syntax errors in other parts of the program. Think about why and then fix these problems by modifying the code appropriately. Enforcing Good Encapsulation The Book class is well-designed: it logically groups data and methods together that semantically define what a book is and how you can use it. The Author class is not well defined though; its data members are publicly exposed and it has no methods at all. 1. Redesign the Author class and make its member variables private. 2. Create and use getter methods to make the members accessible to the outside world. Use these methods where appropriate. 3

3. Create setter methods (also called mutator methods) to enable code outside of the Author class to change the member variables. Add some data validation: for example, do not allow invalid values for member variables. 4. Add and make use of an appropriate constructor to this class. 5. Add a method to return a String that is the author s last name/first name separated by a comma and then utilize it where appropriate (modify the printbooks() method to use this new method instead of formatting the last name/first name directly). Adding and Using Methods The printbooks() method prints out the title, author, and ISBN in a formatted manner one per line. In this activity, you will modify it to output additional information: the year of its publication and its age (the number of years since its publication date). 1. Modify the printbooks method in the LibraryDemo class to output the publication year of each book in another column. Note that the Book class offers a getpublishdate() method already implemented for you. 2. To add the age column, you will need to add a new method to the Book class that returns the number of years between the publish date and today. You may find the following code snippet useful (it utilizes the date/time library provided by Java 8): int years = Period.between(this.publishDate, LocalDate.now()).getYears(); Advanced Activity (Optional) 1. The printbooks() method prints books in the order in which they appear in the list. This isn t as useful as if they were sorted in some manner. Read Oracle s tutorial on Object ordering, http://docs.oracle.com/javase/tutorial/ collections/interfaces/order.html. Write code to use the Collections.sort() method along with an anonymous Comparator<Book> instance to sort the collection according to the book s title. 2. Composition is when a class owns instance(s) of other classes (the Book class owns an instance of the Author class). If different instances of a class A 1 and A 2 are given references to the same object B, then changes are made to B, the changes will be apparent to both A 1 and A 2. Sometimes this behavior is desired. Other times it is not. One common method to prevent this is to define a copy constructor which takes an instance of the class and performs a deep copy of an object by copying each of its fields to the new instance. For example, the copy 4

constructor for the Author class may look something like this: 1 public Author(Author author) { 2 this.firstname = new String(author.firstName); 3 this.lastname = new String(author.lastName); 4 } Design and implement a copy constructor for the Book class and the Library class. How do different fields need to be copied? 5