Week 3 Classes and Objects

Similar documents
CS201 - Assignment 3, Part 1 Due: Friday February 28, at the beginning of class

UML IB Computer Science. Content developed by Dartford Grammar School Computer Science Department

Unit 5: More on Classes/Objects Notes

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

Lecture 5: Implementing Lists, Version 1

Computer Information Systems Classes and Functions Review Lab

CS1083 Week 2: Arrays, ArrayList

CISC-124. Passing Parameters. A Java method cannot change the value of any of the arguments passed to its parameters.

CMPSCI 187: Programming With Data Structures. Review for First Midterm 9 October 2011

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

CISC-124. Dog.java looks like this. I have added some explanatory comments in the code, and more explanation after the code listing.

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

COMP 202 Java in one week

Procedural Java. Procedures and Static Class Methods. Functions. COMP 210: Object-Oriented Programming Lecture Notes 2.

CS1004: Intro to CS in Java, Spring 2005

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 3: SEP. 13TH INSTRUCTOR: JIAYIN WANG

Day 3. COMP 1006/1406A Summer M. Jason Hinek Carleton University

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

Classes Classes 2 / 35

Object Oriented Programming. Week 1 Part 3 Writing Java with Eclipse and JUnit

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

Chapter 4 Defining Classes I

4. Java Project Design, Input Methods

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

CSE 142 Su 04 Computer Programming 1 - Java. Objects

Learning objectives. Reading carefully. Managing your time. CS2110 Fall 2017 Assignment A1. PhD Genealogy. See CMS for the due date

ICOM 4015 Advanced Programming Laboratory. Chapter 4 Introduction to Object Oriented Programming

Lecture 7 Objects and Classes

Annotation Hammer Venkat Subramaniam (Also published at

Introduction to Scientific Programming with C++

Object Oriented Programming

A First Object. We still have another problem. How can we actually make use of the class s data?

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

Example Program. public class ComputeArea {

Comp Assignment 2: Object-Oriented Scanning for Numbers, Words, and Quoted Strings

Software Testing Prof. Meenakshi D Souza Department of Computer Science and Engineering International Institute of Information Technology, Bangalore

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

Classes Classes 2 / 36

Software Design and Analysis for Engineers

CS112 Lecture: Working with Numbers

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

Week 16: More on Collections and Immutability

Object-Oriented Design Lecture 3 CSU 370 Fall 2007 (Pucella) Friday, Sep 14, 2007

ICOM 4015 Advanced Programming Laboratory. Chapter 1 Introduction to Eclipse, Java and JUnit

Week 7 Inheritance. Written by Alexandros Evangelidis. Adapted from Joseph Gardiner. 10 November 2015

Midterms Save the Dates!

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University

Text Input and Conditionals

COMP 250 Fall inheritance Nov. 17, 2017

Lesson 12: OOP #2, Accessor Methods (W03D4)

1.00 Lecture 2. What s an IDE?

CS 1331 Exam 1 ANSWER KEY

IT 313 Advanced Application Development

COSC 2P91. Bringing it all together... Week 4b. Brock University. Brock University (Week 4b) Bringing it all together... 1 / 22

Object Oriented Programming

Stage 11 Array Practice With. Zip Code Encoding

Recommended Group Brainstorm (NO computers during this time)

Review. these are the instance variables. these are parameters to the methods

The NetBeans IDE is a big file --- a minimum of around 30 MB. After you have downloaded the file, simply execute the file to install the software.

Remedial Java - Excep0ons 3/09/17. (remedial) Java. Jars. Anastasia Bezerianos 1

ACORN.COM CS 1110 SPRING 2012: ASSIGNMENT A1

CMPSCI 187: Programming With Data Structures. Lecture #24: Files and a Case Study David Mix Barrington 2 November 2012

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

Basic Keywords Practice Session

Notes on Chapter Three

Data Structures. Data structures. Data structures. What is a data structure? Simple answer: a collection of data equipped with some operations.

CMPSCI 187 / Spring 2015 Postfix Expression Evaluator

Object Oriented Programming

Adding content to your Blackboard 9.1 class

UNDERSTANDING CLASS DEFINITIONS CITS1001

CS/ENGRD 2110 SPRING Lecture 3: Fields, getters and setters, constructors, testing

Static, Final & Memory Management

Hello World! Computer Programming for Kids and Other Beginners. Chapter 1. by Warren Sande and Carter Sande. Copyright 2009 Manning Publications

Lecture 21: The Many Hats of Scala: OOP 10:00 AM, Mar 14, 2018

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

Adam Blank Lecture 3 Autumn 2016 CSE 143. Computer Programming II

CSE 143. More ArrayIntList; pre/post; exceptions; debugging. Computer Programming II. CSE 143: Computer Programming II

3 ADT Implementation in Java

CS 1302 Chapter 9 (Review) Object & Classes

Principles of Object Oriented Programming. Lecture 4

Lecture 14: Exceptions 10:00 AM, Feb 26, 2018

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

Shorthand for values: variables

Chapter 11: Create Your Own Objects

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

Chapter 15: Object Oriented Programming

Java Basics. CSE 373, Fall 2015 Megan Hopp

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

Changing an Object s Properties

CSE / ENGR 142 Programming I

Inf1-OP. Classes with Stuff in Common. Inheritance. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein.

More on Classes. 1 tostring

PRINCIPLES OF SOFTWARE BIM209DESIGN AND DEVELOPMENT 03. REQUIREMENTS CHANGE. I Love You, You re Perfect... Now Change!

Carleton University COMP1406/1006, Summer 2013 Tutorial 2

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

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and More

Creating Your Own Classes

Inf1-OOP. OOP Exam Review. Perdita Stevens, adapting earlier version by Ewan Klein. March 16, School of Informatics

The name of our class will be Yo. Type that in where it says Class Name. Don t hit the OK button yet.

Transcription:

Week 3 Classes and Objects written by Alexandros Evangelidis, adapted from J. Gardiner et al. 13 October 2015 1 Last Week Last week, we looked at some of the different types available in Java, and the problems associated with them. 2 This Week By the end of the tutorial, we should have covered: Conventions Classes and Objects The this keyword Getters and Setters Testing your work 3 Conventions 3.1 Variable Names There are a few things we d like you to know about conventions for naming in Java. Class names generally start with a capital letter: public class MyClass{ As such, the class above would be in a file named MyClass.java. The class will still work if not named starting with a capital letter, but conventions should be adhered to, in order to improve readability. Something else to consider is variable naming: variables, and methods (more on those soon) start with lower case letters: int myintvalue = 4 ; String myname = "Matt" ; Note also the way that I ve named those variables, using something called camel case: each new word in the variable name starts with a capital letter. Again, this is just convention. Some things, like types and methods must start with the correct case you ll have seen this if you ve tried to write system.out.println or string s="...". Names (class names, variable names, method names) should be meaningful. That is, something like MyClass.java should be avoided. 1

3.2 Commenting Remember, it s important to comment your work, so that your tutor can see what you re doing. It s also helpful to you your comments will help you to identify what each part of your work does when you go back to it. Getting into the habit now will serve you well once we start doing more complicated exercises - in future weeks you will lose marks for not commenting, so start now! 3.2.1 Line comments Sometimes, you may just wish to document the function of a single line: String shorterstring=s. substring ( 0, 3 ) ; // take the f i r s t t h r e e c h a r a c t e r s o f s While it s important to use comments to make your code easier to understand, don t overdo it, and in particular, make sure that your comments are meaningful and do not just repeat the code in another language: int i ; // d e c l a r e an i n t c a l l e d i i=3; // s e t i to 3 System. out. println("i is equal to "+i ) ; // p r i n t what i i s equal to This can get quite annoying to read. As a general rule, if someone else in your cohort could easily understand what a line does, don t comment it. 3.2.2 Block comments If a comment is big enough that it has to span more than one line, use a block. These generally go before the code: / Set up a Scanner, read a l i n e o f t e x t and s t o r e in l i n e, p r i n t back to user / Scanner sc = new Scanner( System. in ) ; String line = sc. nextline ( ) ; System. out. println(line ) ; Again, be careful not to overcomment and make sure that it doesn t just paraphrase the code! If the block starts with /** it is taken into the Javadoc documentation. 4 Classes and Objects Being an object-oriented programming language, classes and objects are the very bedrock on which Java is built. Think of a class like a blueprint for something which you re going to build upon later, and objects of that class being implementations of the blueprint that you can actually do something with (i.e., hold data). In the lecture, you saw the classes Date and BankAccount. These classes are simply templates, which represent what information will be stored about each instance Object of type Date and BankAccount. 4.1 So What is an Object? If a class is a blueprint, then an object of that class is an instance of the class. Let s take a couple of examples. I have a class Dog that represents a generic Dog. Of course, it s not possible for someone to just have a generic Dog. They have to have a specific breed of Dog else all Dogs would be the same. Every Dog is an instance object of the class Dog. Let s say that several Dogs live in a kennel. First, we need to set up our Dog class: 2

public class Dog{ // g l o b a l f i e l d s should be d e c l a r e d p r i v a t e ( data e n c a p s u l a t i o n ) private String name ; private String breed ; private int age ; private double weight ; / We don t need a main method, b e c a u s e we don t want t o run Dog on i t s own. We j u s t need a Constructor : / public Dog( String name, String breed, int age, double weight){ this. name=name ; this. breed=breed ; this. age=age ; this. weight=weight ; Notice the keyword this. If I didn t have that, what would happen? The line name=name wouldn t make sense: Java would consider name standing for the parameter two times, therefore only the local version of name (the parameter) will be updated, rather than the field in the object. The keyword this means (in this case) set the name field in this object to be equal to the parameter name. Another way to think of classes and objects is like a spreadsheet. The class is like the column headers the objects are like rows! 4.2 Creating Objects It s all well and good writing Objects, but what do we then do with them? Well, first we need to create or instantiate the Object. For most Objects, the only way to do that is via the new keyword: Dog fido = new Dog("Fido", "Jack Russell", 5, 1 2. 5 ) ; What s going on above? Well, the new keyword tells Java to make room in memory for a new Object, and then calls the constructor of the given class to create the new Object. The arguments you give must exactly match the ones specified in the constructor, or Java may throw errors at you, or you may get wrong results. Now we ve created an object, we can apply methods to it, such as getters or setters... 4.3 Getters, Setters and Testing Often, we ll need to get information from our objects in the example above, we would need to find out what the name, breed, weight or age of each dog was. Note that the class fields for each of these are marked private. That means we can t access them directly, or change them directly we need to use getter and setter methods. 4.3.1 Getters A getter method is used to access the information in an object. Often, it just returns the value of one field: public String getname ( ) { return name ; Note the use of the return keyword. This returns information to from wherever the method was called. If the return type of a method is anything but void, then there must be a return statement in the body of the method. 3

4.3.2 Setters As we already covered, the fields in Dog are private. This means they can only be modified by the class itself via setter methods: public void setname( String name){ this. name=name ; Note that the return type of these methods is generally void. something, and so don t need a return statement. 4.3.3 Other Methods and Testing This is because they don t need to return One of the most important methods in any class is the tostring() method. This returns a String representation of the object, and will usually look like nonsense, unless you redefine it. In our case, we want the tostring method in Dog to tell us everything about a particular dog: public String tostring ( ) { return "Dog name: " + getname ( ) + "; breed: " + getbreed ( ) + "; age: " + getage ( ) + "; weight: " + getweight ( ) + "kg" ; Note that I m using the getter methods to construct the String. This is good practice, as you may want to do something to the values in the fields before they re returned. Now that the Dog class is constructed, I can think about testing it. I can do this initially by creating several instances of Dog in some other class. With each of those instances, I can perform a few operations, and then check that the values are what I expect: public static void main( String [ ] args){ Dog firstdog=new Dog("fred","Yorkshire Terrier", 3, 7. 6 ) ; Dog seconddog=new Dog("bella","Rhodesian Ridgeback", 4, 1 1. 6 ) ; System. out. println(firstdog ) ; System. out. println(seconddog. tostring ( ) ) ; // e q u i v a l e n t to the l i n e above s behaviour firstdog. setage ( 6 ) ; seconddog. setweight ( 1 4. 0 ) ; System. out. println( seconddog. getname()+" is now " +seconddog. getweight()+"kg" ) ; // should be 14.0... 4.3.4 A Simple JUnit test Now, we are going to create a simple JUnit test in order to test the getage() method. Simply put, we want to verify that once we have created a Dog object and its getter is called (in this case the getage()), the correct age is being returned. First, we start by defining a new class DogTest, with the necessary import statements. Note that you do not have to type the import statements explicitly, but these will be automatically generated in Eclipse once you specify the appropriate annotations and JUnit commands, and place your cursor over them. 4

import static org. junit. Assert. ; import org. junit. Test ; public class DogTest { / Testing the getage ( ) method / @Test public void test1 ( ) { Dog firstdog=new Dog("fred","Yorkshire Terrier", 3, 7. 6 ) ; //3 i s what I expect i f getage ( ) i s c a l l e d int expected = 3 ; //The a c t u a l value int firstdogage = firstdog. getage ( ) ; // Note that i t i s a JUnit convention to // put the expected argument f i r s t assertequals( expected, firstdogage ) ; // o r you might want t o add a message // that may help you to debug a t e s t // in case an a s s e r t i o n f a i l s assertequals("test1 of getage() in DogTest", expected, firstdogage ) ; Once the above JUnit test is run, we can note the green bar in Eclipse indicating that the test was successful.in contrast, a red bar indicates that a test has failed. 5