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

Similar documents
Anatomy of a Class Encapsulation Anatomy of a Method

Lecture 06: Classes and Objects

ECE 122. Engineering Problem Solving with Java

Programs as Models. Procedural Paradigm. Class Methods. CS256 Computer Science I Kevin Sahr, PhD. Lecture 11: Objects

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

Constants. Why Use Constants? main Method Arguments. CS256 Computer Science I Kevin Sahr, PhD. Lecture 25: Miscellaneous

CS1004: Intro to CS in Java, Spring 2005

Chapter 4: Writing Classes

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and More

Chapter 4 Defining Classes I

Lecture 7 Objects and Classes

Introduction to Programming Using Java (98-388)

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

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

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

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

Class API. Class API. Constructors. CS200: Computer Science I. Module 19 More Objects

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

CS1004: Intro to CS in Java, Spring 2005

Object Oriented Programming in C#

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

Lecture 5: Methods CS2301

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

Java Review. Fundamentals of Computer Science

Chapter 6 Introduction to Defining Classes

ITI Introduction to Computing II

Object-Oriented Design Lecture 14 CSU 370 Fall 2007 (Pucella) Friday, Nov 2, 2007

Object Oriented Features. Inheritance. Inheritance. CS257 Computer Science I Kevin Sahr, PhD. Lecture 10: Inheritance

Method. Why Write Methods? Overview. CS256 Computer Science I Kevin Sahr, PhD. Lecture 21: Writing Class Methods. ClassName.methodName(arguments)

Review questions. Review questions, cont d. Class Definition. Methods. Class definition: methods. April 1,

Lecture 8 Classes and Objects Part 2. MIT AITI June 15th, 2005

Administration. Classes. Objects Part II. Agenda. Review: Object References. Object Aliases. CS 99 Summer 2000 Michael Clarkson Lecture 7

ITI Introduction to Computing II

public class Foo { private int var; public int Method1() { // var accessible anywhere here } public int MethodN() {

Paytm Programming Sample paper: 1) A copy constructor is called. a. when an object is returned by value

CLASS DESIGN. Objectives MODULE 4

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

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

Computer Science II. OO Programming Classes Scott C Johnson Rochester Institute of Technology

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

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

CS111: PROGRAMMING LANGUAGE II

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

CMSC 132: Object-Oriented Programming II

CHAPTER 7 OBJECTS AND CLASSES

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

CHAPTER 7 OBJECTS AND CLASSES

Java Object Oriented Design. CSC207 Fall 2014

1 Method Signatures and Overloading (3 minutes, 2 points)

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

Programming Language Concepts: Lecture 2

CS313D: ADVANCED PROGRAMMING LANGUAGE

Flow of Control. Conditional Statements. Conditional Statements. CS256 Computer Science I Kevin Sahr, PhD. Lecture 15: The If-Statement

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

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

Recommended Group Brainstorm (NO computers during this time)

Java Fundamentals (II)

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

CS110D: PROGRAMMING LANGUAGE I

Chapter 5: Writing Classes and Enums

Topic 5 Polymorphism. " Inheritance is new code that reuses old code. Polymorphism is old code that reuses new code.

PIC 20A The Basics of Java

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

ECOM 2324 COMPUTER PROGRAMMING II

Sri Vidya College of Engineering & Technology

Discover how to get up and running with the Java Development Environment and with the Eclipse IDE to create Java programs.

Principles of Object Oriented Programming. Lecture 4

1.00 Lecture 6. Java Methods

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

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

Lecture #6-7 Methods

Classes Classes 2 / 35

Object-Oriented Programming Concepts

Software Design and Analysis for Engineers

ITI Introduction to Computing II

Objects and Classes -- Introduction

Chapter 9 Objects and Classes. OO Programming Concepts. Classes. Objects. Motivations. Objectives. CS1: Java Programming Colorado State University

Final Exam CS 152, Computer Programming Fundamentals December 5, 2014

ECE 122. Engineering Problem Solving with Java

Inf1-OOP. Data Types. Defining Data Types in Java. type value set operations. Overview. Circle Class. Creating Data Types 1.

Object-Orientation. Classes Lecture 5. Classes. State and Behaviour. Instance Variables. Object vs. Classes

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

Classes Classes 2 / 36

A foundation for programming. Classes and objects. Overview. Java primitive types. Primitive types Creating your own data types

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

Methods and Data (Savitch, Chapter 5)

After a lecture on cosmology and the structure of the solar system, William James was accosted by a little old lady.

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

Comp 248 Introduction to Programming Chapter 4 & 5 Defining Classes Part B

What will this print?

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

Q1 Q2 Q3 Q4 Q5 Total 1 * 7 1 * 5 20 * * Final marks Marks First Question

Comments are almost like C++

class declaration Designing Classes part 2 Getting to know classes so far Review Next: 3/18/13 Driver classes:

Short Notes of CS201

Object Orientated Analysis and Design. Benjamin Kenwright

An Introduction to C++

Handout 7. Defining Classes part 1. Instance variables and instance methods.

Practice Questions for Chapter 9

Transcription:

1 CS257 Computer Science II Kevin Sahr, PhD Lecture 5: Writing Object Classes Object Class 2 objects are the basic building blocks of programs in Object Oriented Programming (OOP) languages objects consist of attributes and behavior the attributes and behavior are defined in the object class attributes are represented by instance variables behavior consists of the constructors and instance methods the class is a blueprint or template for creating objects every object is an instance of some class 3 EX: LightSwitch Class the LightSwitch class is a template for creating objects that represent light switches the complete class source code, the API, and a program that uses the class are on the website we ll briefly review the class, and then enhance it with new Java features Basic Class Concepts: Parts 4 the LightSwitch class illustrates the 3 major parts of an object class: instance variables constructors instance methods

Basic Class Concepts: Encapsulation 5 the LightSwitch class implements the important OOP concept of encapsulation encapsulation is an important concept in OOP languages, defined by: restricting access to the object internals instance variables are private providing an external interface to those internals as appropriate using service methods public getters/setters (accessors/mutators) provided as appropriate EX: No ison Setter 6 note that the API does not contain a setter for the ison instance variable this means that the designer of the LightSwitch class decided not to allow external users to directly change that value Variable Scoping 7 all variables are defined at the smallest possible scope Instance variables are only created for object state that requires a value for the entire existence of the object variables are declared as local variables whenever possible EX: String s in tostring More OOP features of Java 8 now let s use some new OOP features and Java syntax to improve our basic LightSwitch class to create the class LightSwitch2 the secrets of the tostring() method instance variable initialization this reference helper/support methods class variables and constants class methods method overloading

///// private private ///// public { ison public { ison ///// private private ///// public public { the tostring method revisited the LightSwitch has a tostring method returns a String describing the current state of the object makes it easy to take a snapshot of the object state Note: tostring is automatically invoked when the string is an argument to System.out.println/print used in String concatenation EX: System.out.println(obj); is equivalent to: System.out.println(obj.toString()); 9 Instance Variable Initialization instance variables can be initialized in constructors but if the value is known at compile-time, instance variables can also be initialized when declared, just like other variables allows specifying default values for instance variables no need to duplicate the initialization in multiple constructors good idea to use instance variable initialization when possible ensures that the variable has a value (without relying on the constructor) ensures there is only one consistent default value 10 Example LightSwitch instance variables and first two constructors: instance data variables boolean ison; int ; constructors LightSwitch () = false; // originally "off" = 0; // not switched yet // method LightSwitch 11 LightSwitch (int In) = In; = false; // originally "off" // method LightSwitch Example can be rewritten using instance variable initialization in LightSwitch2: 12 instance data variables boolean ison = false; int = 0; constructors LightSwitch2 () { LightSwitch2 (int In) = In; // method LightSwitch2

int ison int this.ison this. The this Reference 13 The this reference allows an object to refer to itself used inside an instance method, it refers to the object upon which the method was invoked EX: Suppose the this reference is used inside a method called tryme, which is invoked as follows: obj1.tryme(); obj2.tryme(); Inside tryme()the this reference refers to obj1 in the first invocation; in the second it refers to obj2 Avoiding Naming Conflicts 14 public LightSwitch (boolean ison, int ) Constructor for a LightSwitch with the specified on-state and number of times flipped. public LightSwitch (boolean isonin, In) { compiler must = isonin; be able to = In; distinguish between // method LightSwitch argument and instance variable 14 The this reference and Naming Conflicts The this reference can be used to distinguish the instance variables of a class from corresponding method arguments with the same names common in constructors and setters 15 argument names can match those in the API public LightSwitch2 (boolean ison, ){ = ison; = ; // method LightSwitch2 Helper/Support Methods 16 all of the methods we have seen so far have been service methods public visibility meant to provide capabilities to external users of our class often it is useful to define methods that are used internally by methods in the class can replace code that is duplicated in multiple service methods can simplify the logic of the service methods we call these methods helper or support methods private visibility not available to external users of our class not listed in the class API

if s s s return String if s s return Helper Method Example the LightSwitch tostring method includes some code that assigns a String to the ison state: public String tostring() { String s = new String("The switch is "); 17 (ison) = s + "ON"; else = s + "OFF"; = s + " and has been flipped " + + " times."; s; // method tostring Example in LightSwitch2 let s create a helper method to do that part: 18 private String isonstring() { s; (ison) = "ON"; else = "OFF"; s; // method isonstring Example 19 now the LightSwitch2 tostring method simplifies to: public String tostring() { return "The switch is " + isonstring() + " and has been flipped " + + " times."; // method tostring Static Class Members 20 Recall that a class (or 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 referred to as class variables Determining if a method or variable should be static is an important design decision

The static Modifier 21 We declare class methods and variables using the static modifier the method or variable is associated with the class, rather than with a specific object of that class Let's carefully consider the implications Instance Variables Review 22 instance variables are associated with class instances: objects of that class Each object has its own copy of all instance variables defined in the class Memory is allocated for the object s instance variables when the object is instantiated (using the new operator) Changing the value of one object s instance variable has no effect on any other objects Class Variables 23 class variables are declared with the keyword static private static float someclassvar; only one copy of each class variable exists memory for each class variable is allocated when the class is first referenced all instances of the class share its class variables changing the value of a class variable in one object changes it for all others there is only one! Visibility of Class Variables 24 like instance variables, encapsulation warrants that most class variables be declared private exception: if a class variable is a constant it can be public since a constant can t be changed by external (or internal) users, this doesn t break encapsulation EX: the Math class contains a constant class variable declared: public static final double PI = 3.141592653589793; external users can access this constant as Math.PI

EX: Adding a Constant 25 let s say that at most 100 lights can be on at the same time since we don t want to use magic numbers, let s add a constant to LightSwitch2 public static final int MAX_LIGHTS_ON = 100; external users can access (but not change) the value of this constant using LightSwitch2.MAX_LIGHTS_ON public constants should also be added to the API Constants public static final int MAX_LIGHTS_ON The maximum number of lights than can be on at one time. Class Variables EX now let s add a class variable to LightSwitch2 to keep track of how many light switches are currently on 26 to enforce encapsulation the class variable will be private we ll define a public class method to provide the value to external users - since it s public, we ll also add it to the API we intentionally won t create a method that let s external users change the value Class Variables EX Code 27 first declare and initialize the class variable: private static int numlightson = 0; define a class service method to provide the value to external users: public static int getnumlightson () { return numlightson; Class Methods and Variables 28 class methods and class variables often work together class methods are not associated with a particular object instance, so they can not use instance variables but a class method can use class variables note: instance methods can use class variables (as well as instance variables)

Class Variables EX (continued) 29 we also need to find every method in LightSwitch2 where a light is turned on or off and update numlightson accordingly there are two: the third constructor and the flip method we also need to make sure we don t have too many lights on since we need to do this in multiple places, let s add a helper method turnon that handles the check Class Variables EX Helper Method 30 the turnon helper method: private void turnon() { if (numlightson >= MAX_LIGHTS_ON) System.out.println( ERROR: can not turn on another light."); else { this.ison = true; numlightson++; Class Variables EX Constructor change the third constructor to: 31 public LightSwitch2(boolean ison, int ){ if (ison) turnon(); // try to turn on else this.ison = ison; // set to false this. = ; // method LightSwitch2 Class Variables EX flip method change the flip method to: 32 public void flip() { if (ison) { ison = false; numlightson--; else { turnon(); = + 1; // method flip

Method Overloading 33 Method overloading is the process of giving a single method name multiple definitions If a method is overloaded, the method name is not sufficient to determine which method is being called The signature of each overloaded method must be unique The signature consists of the method name along with the number, type, and order of the arguments Method Overloading 34 The compiler determines which method is being invoked by analyzing the arguments float tryme(int x) { return x +.375; Invocation result = tryme(25, 4.32) float tryme(int x, float y) { return x*y; EX: The println Method 35 The println method is overloaded: println (String s) println (int i) println (double d) and so on... The following lines invoke different versions of the println method: System.out.println ("The total is:"); System.out.println (total); Overloading Methods 36 The return type of the method is not part of the signature That is, overloaded methods cannot differ only by their return type Constructors are often overloaded Overloaded constructors provide multiple ways to initialize a new object

Method Overloading EX the three constructors in LightSwitch2 are an example of method overloading our current flip method takes no arguments and flips the light switch a single time let s add an overloaded flip method that flips the light switch multiple times the method signature will have one argument, rather than zero note that this flip method calls the original (no argument) flip method public void flip(int numtimes) { for (int i = 0; i < numtimes; i++) flip(); // method flip 37 LightSwitch2 EX 38 the source code file LightSwitch2.java, the class API, and a program LightSwitchApp2.java that uses LightSwitch2 objects are available on the class website spend some time looking at this example you can easily test the handling of the max number of lights on by temporarily changing MAX_LIGHTS_ON to a smaller number Account Class EX 39 the Account class is a more complex object class it includes all of the new features discussed in this lecture the source code file Account.java and a program that uses the class (Transactions.java) are available on the class website spend some time understanding this class Lecture 5 Vocabulary 40 this reference helper/support methods class variables method overloading method signature