Defining Your Own Classes

Similar documents
COP 3330 Final Exam Review

Chapter 4 Defining Classes I

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

Goal. Generic Programming and Inner classes. Minor rewrite of linear search. Obvious linear search code. Intuitive idea of generic linear search

(a) in assignment statements. (b) when invoking methods (with objects as parameters) (d) equality of references versus equality of objects

Lecture 5: Implementing Lists, Version 1

And Even More and More C++ Fundamentals of Computer Science

ITI Introduction to Computing II

Motivation was to facilitate development of systems software, especially OS development.

Programming Problems 22nd Annual Computer Science Programming Contest

CMSC 341 Lecture 7 Lists

CSCI-1200 Data Structures Spring 2018 Lecture 14 Associative Containers (Maps), Part 1 (and Problem Solving Too)

Motivation was to facilitate development of systems software, especially OS development.

Data abstractions: ADTs Invariants, Abstraction function. Lecture 4: OOP, autumn 2003

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

CS 231 Data Structures and Algorithms, Fall 2016

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

Lecture 8: Iterators and More Mutation

More on Classes. The job of this method is to return a String representation of the object. Here is the tostring method from the Time class:

Chapter 11: Create Your Own Objects

Programming Languages and Techniques (CIS120)

Chapter 3 Classes. Activity The class as a file drawer of methods. Activity Referencing static methods

Class 15. Object-Oriented Development from Structs to Classes. Laura Marik Spring 2012 C++ Course Notes (Provided by Jason Minski)

CS201 - Assignment 3, Part 2 Due: Wednesday March 5, at the beginning of class

LAB 7. Objectives: Navin Sridhar D 8 54

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

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

COMP-202 Unit 8: Defining Your Own Classes. CONTENTS: Class Definitions Attributes Methods and Constructors Access Modifiers and Encapsulation

Unit 4: Client View of a Component Methods

static CS106L Spring 2009 Handout #21 May 12, 2009 Introduction

QUIZ. What is wrong with this code that uses default arguments?

ITI 1120 Lab #9. Slides by: Diana Inkpen, Alan Williams, Daniel Amyot Some original material by Romelia Plesa

Introduction to Linked Data Structures

Array Basics: Outline. Creating and Accessing Arrays. Creating and Accessing Arrays. Arrays (Savitch, Chapter 7)

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

Object Oriented Programming in C#

Assignment 4. Aggregate Objects, Command-Line Arguments, ArrayLists. COMP-202B, Winter 2011, All Sections. Due: Tuesday, March 22, 2011 (13:00)

ASSIGNMENT 5 Data Structures, Files, Exceptions, and To-Do Lists

CONTENTS: While loops Class (static) variables and constants Top Down Programming For loops Nested Loops

EXPRESSIONS AND ASSIGNMENT CITS1001

CS 103 Unit 11. Linked Lists. Mark Redekopp

MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012

ECE 122. Engineering Problem Solving with Java

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods

CS Introduction to Programming Midterm Exam #1 - Prof. Reed Spring 2010

Definition: A data structure is a way of organizing data in a computer so that it can be used efficiently.

Chapter 4: Writing Classes

Inheritance (IS A Relationship)

Declarations and Access Control SCJP tips

BM214E Object Oriented Programming Lecture 8

CS 163 Practice Final Exam Winter 2012

Arrays. Here is the generic syntax for an array declaration: type[] <var_name>; Here's an example: int[] numbers;

CS112 Lecture: Defining Classes. 1. To describe the process of defining an instantiable class

Lecture 36: Cloning. Last time: Today: 1. Object 2. Polymorphism and abstract methods 3. Upcasting / downcasting

Object-oriented Programming and Software Engineering CITS1001. Multiple-choice Mid-semester Test

Variables. Data Types.

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

C:\Temp\Templates. Download This PDF From The Web Site

Singly linked lists in C.

Data Structures and Algorithms in Java. Second Year Software Engineering

Example: Computing prime numbers

Functions, Pointers, and the Basics of C++ Classes

Chapter 9 Enumerations

CS 211 Programming Practicum Spring 2018

Programming Language. Functions. Eng. Anis Nazer First Semester

Two Types of Types. Primitive Types in Java. Using Primitive Variables. Class #07: Java Primitives. Integer types.

CS100J, Fall 2003 Preparing for Prelim 1: Monday, 29 Sept., 7:30 9:00PM

CS111: PROGRAMMING LANGUAGE II

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

CS112 Lecture: Working with Numbers

CPS122 Lecture: Detailed Design and Implementation

COMP-202 Unit 4: Programming with Iterations

Reviewing for the Midterm Covers chapters 1 to 5, 7 to 9. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

University of Palestine. Mid Exam Total Grade: 100

Programming Assignment 1

Chapter 1b Classes and Objects

Programming 2. Topic 8: Linked Lists, Basic Searching and Sorting

CS 2102 Exam 2 B-Term 2013

8 Understanding Subtyping

Dynamic Memory Allocation

Common Misunderstandings from Exam 1 Material

2-D Arrays. Of course, to set each grid location to 0, we have to use a loop structure as follows (assume i and j are already defined):

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

CSC-140 Assignment 6

Unit 7. 'while' Loops

Array. Prepared By - Rifat Shahriyar

CS/ENGRD 2110 FALL Lecture 5: Local vars; Inside-out rule; constructors

CS 103 Unit 11. Linked Lists. Mark Redekopp

3.1 Class Declaration

News and information! Review: Java Programs! Feedback after Lecture 2! Dead-lines for the first two lab assignment have been posted.!

Assignment 6: Dodo keeps getting smarter

Procedural Abstraction

Tail Calls. CMSC 330: Organization of Programming Languages. Tail Recursion. Tail Recursion (cont d) Names and Binding. Tail Recursion (cont d)

CSE 143 SAMPLE MIDTERM

Array Based Lists. Collections

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

Seminar on Simulation of Telecommunication Sistems. Introduction to object-oriented programming: C++

Exam Duration: 2hrs and 30min Software Design

CMSC131. Library Classes

Procedures, Parameters, Values and Variables. Steven R. Bagley

Transcription:

Defining Your Own Classes In C, you are allowed to define a struct and then define variables of that struct. But Java allows you to define your own class. This means not only defining the data structure, but also definition the methods (functions) that operate solely on objects of the class. Here are the components of a class: 1) Instance Variables 2) Constructor(s) 3) Methods The instance variables specify the different data components of an object of the class. The constructor technically creates and initializes the object and returns a reference to it. But, really in the code that you write, all you need to do is initialize the instance variables of the object. Each instance (non-static) method you write only gets executed if it is called with a specific object. (Remember when we called methods from the String class?) Thus, it is understood that whenever an instance variable is mentioned in an instance method, it refers to the instance variable of the object the method was called on. In particular, each instance method provides some sort of functionality that will allow the user to manipulate objects of your class that they create.

Types of Variables in an instance method: 1) Instance Variables 2) Formal Parameters 3) Local Variables Each of these is a different kind of variable. Even though you are allowed to, do NOT name variables of these different "types" the same name. It will cause confusion, I guarantee it. (Java has rules that specify which of the variables you are referring to if the name is ambiguous.) As already mentioned, instance variables belong to the object the method was called on. The formal parameters serve the same purpose they do in all methods - they are the input the method needs to complete its task. Local variables also serve the same purpose in instance methods as all methods. (Note: This handout is included on the class website.) Here is a portion of the Time class handout: public class Time { private int hours; private int minutes; public Time(int m) { hours = m/60; minutes = m%60; private int totalminutes() { return 60*hours+minutes;

public boolean equals(time time2) { if (this.totalminutes() == time2.totalminutes()) return true; else return false; public Time addtime(time time2) { Time temp = new Time(min); return temp; public String tostring() { return (hours+" hours and "+minutes+" minutes"); The two instance variables that comprise a Time object are two integers: hours and minutes. You'll notice that the constructor's job is simply to initialize the object. Generally the parameters of a constructor are used to initialize (set the values of) the instance variables. (Remember how this works when it is called...the constructor allocates space for the object and returns a reference to that newly created object. However, these details are hid from you even when you write the constructor! So, all you have to do is initialize the instance variables based on the formal parameters when you write the constructor.)

What NOT to do in a constructor: 1) Mistake the left&right hand sides of assignment statements. 2) Create local variables with the names of either the formal parameters OR instance variables. A Note of Visibility Modifiers For now, the only visibility modifiers we will use are public and private. These indicate where an instance variable or method may be accessed. In particular if something is private, it may only be referred to within the class. If something is public, it can be used anywhere. The general rule of thumb is that all instance variables are made private. The reason is that classes allow us to create abstract data types. This means that a person can USE an object without knowing HOW it is stored or HOW the methods in the class work. If other programmers are given access to the instance variables of the objects they create, then they have the power to manipulate the object any way they want. BUT, in order to use this power effectively, the user must understand the details of HOW the object works. THIS DEFEATS THE WHOLE PURPOSE OF FORMING CLASSES IN THE FIRST PLACE!!! Generally, most methods are made public so that others can use them. However, it is not inconceivable to design a private method. Consider the totalminutes method in the Time class above. There is no need to allow someone USING the class to

call this method. Rather, I have simply written it so that I can carry out other methods (such as equals and addtime) with a more efficient design. Since the purpose of the method is internal to making other methods in the class, I have chosen to make it private. Use of this You'll notice that inside of the equals() method I have used an object called this. This can ONLY be used inside of an instance method of a class. In particular, this refers to the object the method was called on. I wrote it in this method to be explicit. If you look at the line: if (this.totalminutes() == time2.totalminutes()) you'll see that the boolean expression is comparing the total number of minutes in the object the method is called on WITH the total number of minutes in the object time2. Although I have been explicit here, it was not necessary to do so. Consider this line from the addtime method: Whenever an instance method call is made without the object specified inside of another instance method, the call is AUTOMATICALLY made on the object the original method was called on, (which is this.) There are some cases where it is necessary to use this, but usually, one can get away without using it. Standard convention is to do so - my guess is simply to save typing.

Consider the constructor rewritten with these two assignment statements: this.hours = m/60; this.minutes = m%60; This (no pun intended) seems like a little overkill... addtime Method In this method I take in a Time object and return a Time object as well. (Notice the similarity of this prototype to that of several methods in the String class, such as concat.) Here is the code again: public Time addtime(time time2) { Time temp = new Time(min); return temp; In order to complete the task, I first need to compute the sum of the minutes in both objects(this and time2). I do this in the first line using the totalminutes method. Next, I need to create a Time object using the computed information. This can be done with a call to the constructor. Finally, I need to return a reference to the newly created object. (This is temp.) As we can see here, what all the String methods that return a String must do is make a call to a String constructor inside the method and return a reference to that object that was created.

Alternate version of addtime If we wanted addtime to automatically change the current object to the sum of the two times instead of returning a new object, we could write it as follows: public void addtime(time time2) { hours = min/60; minutes = min%60; Once again, we must calculate the sum of the total number of minutes in the current object and time2. But, after this calculation, rather than creating a new object, what we want to do is change the current object to reflect this time. We can do this by resetting both the hours and minutes components of the current object as shown above. Thus, when this method is called (as opposed to the previous one), the object the method is called upon changes to store the sum of its "old" time and time2's time.