CS1004: Intro to CS in Java, Spring 2005

Similar documents
Interfaces. Quick Review of Last Lecture. November 6, Objects instances of classes. Static Class Members. Static Class Members

ECE 122. Engineering Problem Solving with Java

CS1004: Intro to CS in Java, Spring 2005

ECE 122. Engineering Problem Solving with Java

Learning objectives: Enhancing Classes. CSI1102: Introduction to Software Design. More about References. The null Reference. The this reference

Chapter 5: Enhancing Classes

References. Chapter 5: Enhancing Classes. Enhancing Classes. The null Reference. Java Software Solutions for AP* Computer Science A 2nd Edition

CSI Introduction to Software Design. Prof. Dr.-Ing. Abdulmotaleb El Saddik University of Ottawa (SITE 5-037) (613) x 6277

Object Class. EX: LightSwitch Class. Basic Class Concepts: Parts. CS257 Computer Science II Kevin Sahr, PhD. Lecture 5: Writing Object Classes

&KDSWHU(QKDQFLQJ&ODVVHV

Anatomy of a Class Encapsulation Anatomy of a Method

Object-Oriented Design. Chapter

Object-Oriented Design. Chapter. Class Relationships. Classes in a software system can have various types of relationships to each other

Chapter 4: Writing Classes

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

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

ECE 122. Engineering Problem Solving with Java

Encapsulation. You can take one of two views of an object: internal - the structure of its data, the algorithms used by its methods

COSC 121: Computer Programming II. Dr. Bowen Hui University of Bri?sh Columbia Okanagan

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

Packages & Random and Math Classes

CS1004: Intro to CS in Java, Spring 2005

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

CSE 403: Software Engineering, Spring courses.cs.washington.edu/courses/cse403/15sp/ UML Class Diagrams. Emina Torlak

CS 251 Intermediate Programming Inheritance

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

Chapter 5: Writing Classes and Enums

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

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

Chapter 4 Defining Classes I

COMP 202. More on OO. CONTENTS: static revisited this reference class dependencies method parameters variable scope method overloading

COMP 202. More on OO. CONTENTS: static revisited this reference class dependencies method parameters variable scope method overloading

Table of Contents Date(s) Title/Topic Page #s. Chapter 4: Writing Classes 4.1 Objects Revisited

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

CS112 Lecture: Working with Numbers

Classes Classes 2 / 35

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

Design and UML Class Diagrams

Agenda CS121/IS223. Reminder. Object Declaration, Creation, Assignment. What is Going On? Variables in Java

COP 3330 Final Exam Review

ECE 122. Engineering Problem Solving with Java

ECE 122. Engineering Problem Solving with Java

Inheritance. Quick Review of Last Lecture. November 12, Passing Arguments. Passing Arguments. Variable Assignment Revisited

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

Java Review. Java Program Structure // comments about the class public class MyProgram { Variables

Lecture 9: Lists. MIT-AITI Kenya 2005

CS162: Introduction to Computer Science II. Primitive Types. Primitive types. Operations on primitive types. Limitations

PROGRAMMING FUNDAMENTALS

COMP-202. Objects, Part III. COMP Objects Part III, 2013 Jörg Kienzle and others

CITS1001 week 4 Grouping objects lecture 2

CS121/IS223. Object Reference Variables. Dr Olly Gotel

Lecture Transcript While and Do While Statements in C++

CS112 Lecture: Defining Instantiable Classes

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

Chapter 6 Introduction to Defining Classes

CS112 Lecture: Variables, Expressions, Computation, Constants, Numeric Input-Output

Inheritance and Polymorphism

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

COE318 Lecture Notes Week 3 (Week of Sept 17, 2012)

IMACS: AP Computer Science A

Administration. Objects and Arrays. Objects. Agenda. What is an Object? What is a Class?

Interfaces, Testing, and Layout Managers

CS 251 Intermediate Programming Methods and More

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

Equality for Abstract Data Types

11/19/2014. Objects. Chapter 4: Writing Classes. Classes. Writing Classes. Java Software Solutions for AP* Computer Science A 2nd Edition

Last Time. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings

Express Yourself. Writing Your Own Classes

Objects and Classes. Amirishetty Anjan Kumar. November 27, Computer Science and Engineering Indian Institue of Technology Bombay

Type Checking and Type Equality

3 Getting Started with Objects

Java Programming Lecture 7

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

UMBC CMSC 331 Final Exam

Objects and Classes -- Introduction

Chapter 6 Reflection

Classes Classes 2 / 36

Software Development Activities. Establishing the requirements. Software Design. CMPT 126: Lecture 8 Object-Oriented Design

CMPT 126: Lecture 8 Object-Oriented Design

Computer Science II (20082) Week 1: Review and Inheritance

Methods and Data (Savitch, Chapter 5)

Enums. In this article from my free Java 8 course, I will talk about the enum. Enums are constant values that can never be changed.

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

Course Description. Learn To: : Intro to JAVA SE7 and Programming using JAVA SE7. Course Outline ::

Program Development. These activities are not strictly linear they overlap and interact

1B1b Classes in Java Part I

CS 251 Intermediate Programming Java Basics

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

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

CS162: Introduction to Computer Science II

Programming II (CS300)

Methods. Methods. Mysteries Revealed

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

COMP 250 Fall inheritance Nov. 17, 2017

CS 151. Exceptions & Javadoc. slides available on course website. Sunday, September 9, 12

GDB Tutorial. A Walkthrough with Examples. CMSC Spring Last modified March 22, GDB Tutorial

CS 251 Intermediate Programming Methods and Classes

BM214E Object Oriented Programming Lecture 8

JAVA An overview for C++ programmers

Procedural Abstraction

Transcription:

CS1004: Intro to CS in Java, Spring 2005 Lecture #23: OO Design, cont d. Janak J Parekh janak@cs.columbia.edu Administrivia HW#5 due Tuesday And if you re cheating on (or letting others see your) HW#5 don t By the way, we do check for cheaters across sections! OO design aspects in Java We ll look at various Java constructs to help enforce OO paradigms, including: Static variables and methods, revisited How multiple classes can relate to each other Interfaces: contracts for classes Enumerated types, redux Method design 1

Integrated Development Environments (IDEs( IDEs) Quick detour we ve learned how to write Java code in emacs/javac,, but that s s not the only way In fact, there are specialized tools for Windows/Macs that you can also use that integrate the various steps of development (hence, IDE) Two most popular Java ones are: Eclipse (http://( http://www.eclipse.org) NetBeans (http://www.netbeans.org) Suggestion: for Eclipse, use the latest beta version of 3.1 (3.1M6) for full Java 5 support You need Java installed on your machine first Let s s take a look Pros and cons Pros Nice editor, automatically shows errors Easy to compile, run GUI editors, integrated documentation Integrated debugger Cons Project-based based,, which is useful, but requires additional setup Encourages you to design and use your own packages, which isn t t required for this class Requires a fair amount of computing power A bazillion options and buttons; very confusing at first Eclipse or NetBeans? No straight answer I primarily use Eclipse because Emacs keybindings built-in in I like its look and feel Auto-compiles On the other hand, I use NetBeans for GUI editing Eclipse has an optional download, but not quite so robust You are not required to use either If you want to try it out, be my guest, but leave some time for it Post questions on the webboard,, we ll try to help 2

Static Class Members Recall that a static method is one that can be invoked through its class name For example, the methods of the Math class are static: result = Math.sqrt(25); Variables can be static as well Determining if a method or variable should be static is an important design decision The static Modifier We declare static methods and variables using the static modifier It associates the method or variable with the class rather than with an object of that class Static methods are sometimes called class methods and static variables are sometimes called class variables Let's carefully consider the implications of each Static Variables Normally, each object has its own data space, but if a variable is declared as static, only one copy of the variable exists private static float price; Memory space for a static variable is created when the class is first referenced All objects instantiated from the class share its static variables Changing the value of a static variable in one object changes it for all others 3

Static Methods Example: utility methods are often static class Helper { public static int cube (int num) { return num * num * num; } } Because it s static, we can execute Helper.cube( ) directly The order of the modifiers can be interchanged, but by convention visibility modifiers come first No benefit to creating lots of Helper objects On the other hand, we might create a Cube class, where length is an instance variable then, we can t make calculatearea() static Static Class Members Recall that the main method is static it is invoked by the Java interpreter without creating an object Static methods cannot reference instance variables because instance variables don't exist until an object exists Common error: instance variables in the same class as the main method However, a static method can reference static variables or local variables main can instantiate the same class This may sound unintuitive, but if you want to access member variables in a class from within its main method: First, instantiate that class as a variable; Then, access the member through that variable declaration If you don t t like this, feel free to put main in a different class What we ve been doing all along Quick example 4

When use static variables? Static methods and static variables often work together Common paradigm: counter variable that keeps track of the number of objects that was instantiated L/L pages 294, 295 There are indeed other ways to do this, too Have a storage class that keeps track When in doubt, avoid it Class Relationships Classes in a software system can have various types of relationships to each other Three of the most common relationships: Dependency: A uses B Aggregation: A has-a B Inheritance: A is-a B Inheritance is largely beyond the scope of this class; take a look at L/L chapter 8 for more info Dependency A dependency exists when one class relies on another in some way, usually by invoking the methods of the other We've seen dependencies in many previous examples We don't want numerous or complex dependencies among classes, nor complex classes that don't depend on others A good design strikes the right balance 5

Aggregation An aggregate is an object that is made up of other objects has-a a relationship A car has a chassis In software, an aggregate object contains references to other objects as instance data The aggregate object is defined in part by the objects that make it up This is a special kind of dependency the aggregate usually relies on the objects that compose it Aggregation In the following example, a Student object is composed, in part, of Address objects A student has an address (in fact each student has two addresses) An aggregation association is shown in a UML class diagram using an open diamond at the aggregate end See L/L pages 304-307 307 for the code Aggregation in UML StudentBody + main (args : String[]) : void Address - streetaddress : String - city : String - state : String - zipcode : long Student - firstname : String - lastname : String - homeaddress : Address - schooladdress : Address + tostring() : String + tostring() : String 6

The this Reference The this reference allows an object to refer to itself That is, the this reference, used inside a method, refers to the object through which the method is being executed Suppose the this reference is used in a method called tryme,, which is invoked as follows: obj1.tryme(); obj2.tryme(); In the first invocation, the this reference refers to obj1; in the second it refers to obj2 The this Reference The this reference can be used to distinguish the instance variables of a class from corresponding method parameters with the same names public Account (String name, long acctnumber, double balance) { this.name = name; this.acctnumber = acctnumber; this.balance = balance; } Interfaces A Java interface is a collection of abstract methods and constants An abstract method is a method header without a method body An abstract method can be declared using the modifier abstract,, but because all methods in an interface are abstract, usually it is left off An interface is used to establish a set of methods that a class will implement 7

Interfaces interface is a reserved word None of the methods in an interface are given public interface Doable a definition (body) { public void dothis(); public int dothat(); public void dothis2(float value, char ch); public boolean dotheother(int num); } A semicolon immediately follows each method header Why interfaces? Interfaces are commonly called a contract that a class agrees to by implementing the interface You d d do this for one of several reasons: You want your buddy to implement part of the assignment, and want to tell him what to name his methods, variables, return types, etc. (Useful in design, but not for this class!) You want to write an algorithm/program that can easily work with many different objects that all need to have some common functionality For our Blackjack design yesterday, we might make a Player interface with two implementations: a user player and a computer player Interfaces An interface cannot be instantiated Methods in an interface have public visibility by default A class formally implements an interface by: stating so in the class header providing implementations for each abstract method in the interface If a class asserts that it implements an interface, it must define all methods in the interface 8

Interfaces public class CanDo implements Doable { public void dothis () { // whatever } implements is a reserved word public void dothat () { // whatever } Each method listed in Doable is given a definition } // etc. Interfaces A class that implements an interface can implement other methods as well In addition to (or instead of) abstract methods, an interface can contain constants (Remember that constants are declared via public static int or something similar) When a class implements an interface, it gains access to all its constants A class can also implement multiple interfaces; separate them with a comma Interfaces The Java standard class library contains many helpful interfaces The Comparable interface contains one abstract method called compareto,, which is used to compare two objects We discussed the compareto method of the String class; since it s s there, String can implement Comparable What s s the use of implementing Comparable? 9

Easy way to sort an array in Java There s s a static method in the Arrays class (in java.util) ) called sort It can sort primitives: ints,, doubles, floats, etc. For objects, it can sort them if they implement Comparable In other words, it can sort any object as long as it implements the Comparable interface Fundamental idea: Java s s sort code doesn t t care what your object is, as long as it knows it can compare two of them at a time Let s s do a quick example, but note, you can t use this for HW5 The Iterator Interface Recall that an iterator is an object that provides a means of processing a collection of objects one at a time An iterator is created formally by implementing the Iterator interface, which contains three methods: hasnext,, next, and remove By having a class implement the Iterator interface, you can use the compact version of the for loop We ll discuss this further when we talk about ArrayLists in a few weeks Enumerated Types Earlier, we introduced enumerated types,, which define a new data type and list all possible values of that type enums actually define a special class with those values as constants You can set up special constructors and methods We could have used enums for Rock-Paper Paper- Scissors 10

Enumerated Types Every enumerated type contains a static method called values that returns a list of all possible values for that type The list returned from values is an iterator,, so a for loop can be used to process them easily A carefully designed enumerated type provides a versatile and type-safe mechanism for managing data Next time Finish OO design Return to some theory topics 11