Objects and Classes -- Introduction

Similar documents
Anatomy of a Class Encapsulation Anatomy of a Method

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

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

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

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

Chapter 4: Writing Classes

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

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

Packages & Random and Math Classes

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

We now start exploring some key elements of the Java programming language and ways of performing I/O

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

Container Vs. Definition Classes. Container Class

Objectives of CS 230. Java portability. Why ADTs? 8/18/14

A variable is a name for a location in memory A variable must be declared

Chapter 4 Defining Classes I

ECE 122. Engineering Problem Solving with Java

ECE 122. Engineering Problem Solving with Java

ECE 122. Engineering Problem Solving with Java

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

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

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

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

Designing Classes. Where do objects come from? Where do objects come from? Example: Account datatype. Dr. Papalaskari 1

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

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

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

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

Where do objects come from? Good question!

Lab5. Wooseok Kim

COMP 202. Built in Libraries and objects. CONTENTS: Introduction to objects Introduction to some basic Java libraries string

CSC 1051 Data Structures and Algorithms I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

Lab5. Wooseok Kim

CSC 1051 Data Structures and Algorithms I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

Chapter 1. Introduction

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

JAVA GUI PROGRAMMING REVISION TOUR III

Using Classes and Objects Chapters 3 Creating Objects Section 3.1 The String Class Section 3.2 The Scanner Class Section 2.6

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

&KDSWHU(QKDQFLQJ&ODVVHV

Using Java Classes Fall 2018 Margaret Reid-Miller

Object-Oriented Programming Concepts

Using Classes and Objects. Chapter

ECE 122. Engineering Problem Solving with Java

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

Class object initialization block destructor Class object

CPS122 Lecture: Defining a Class

Data and Expressions. Outline. Data and Expressions 12/18/2010. Let's explore some other fundamental programming concepts. Chapter 2 focuses on:

CS112 Lecture: Defining Instantiable Classes

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

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

Defining Classes and Methods

CS 302: INTRODUCTION TO PROGRAMMING IN JAVA. Lecture 16

CMSC 132: Object-Oriented Programming II

Objectives. Problem Solving. Introduction. An overview of object-oriented concepts. Programming and programming languages An introduction to Java

STUDENT LESSON A5 Designing and Using Classes

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

Objects and Classes: Working with the State and Behavior of Objects

Chap. 3. Creating Objects The String class Java Class Library (Packages) Math.random() Reading for this Lecture: L&L,

Programming overview

CS1004: Intro to CS in Java, Spring 2005

COP 3330 Final Exam Review

Introduction to Visual Basic and Visual C++ Introduction to Java. JDK Editions. Overview. Lesson 13. Overview

Table of Contents Date(s) Title/Topic Page #s. Abstraction

Arrays. Outline 1/7/2011. Arrays. Arrays are objects that help us organize large amounts of information. Chapter 7 focuses on:

boolean, char, class, const, double, else, final, float, for, if, import, int, long, new, public, return, static, throws, void, while

JAVA: A Primer. By: Amrita Rajagopal

Introduction to Programming Using Java (98-388)

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity.

Do not start the test until instructed to do so!

Full file at

Introduction to Objects. James Brucker

Lecture 5: Methods CS2301

CISC-124. This week we continued to look at some aspects of Java and how they relate to building reliable software.

Non-instantiable Classes

EECS168 Exam 3 Review

Designing Classes part 2

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG

Flexible data exchange with a method Parameters and return value

COMP-202 Unit 5: Basics of Using Objects

Chapter 6 Introduction to Defining Classes

Defining Classes and Methods

CS/B.TECH/CSE(OLD)/SEM-6/CS-605/2012 OBJECT ORIENTED PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70

CS313D: ADVANCED PROGRAMMING LANGUAGE

c) And last but not least, there are javadoc comments. See Weiss.

Programming Language Concepts: Lecture 2

Methods and Data (Savitch, Chapter 5)

OBJECTS AND CLASSES CHAPTER. Final Draft 10/30/2011. Slides by Donald W. Smith TechNeTrain.com

CS110D: PROGRAMMING LANGUAGE I

SCHOOL OF COMPUTING, ENGINEERING AND MATHEMATICS SEMESTER 1 EXAMINATIONS 2015/2016 CI101 / CI177. Programming

ECE 122. Engineering Problem Solving with Java

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

Object Oriented Methods : Deeper Look Lecture Three

Lecture 7: Classes and Objects CS2301

Chapter 7 User-Defined Methods. Chapter Objectives

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Transcription:

Objects and Classes -- Introduction Now that some low-level programming concepts have been established, we can examine objects in more detail Chapter 4 focuses on: the concept of objects the use of classes to create objects using predefined classes defining methods and passing parameters defining classes visibility modifiers static variables and methods method overloading 1

Objects An object has: state - descriptive characteristics behaviors - what it can do (or be done to it) For example, a particular bank account has an account number has a current balance can be deposited into can be withdrawn from 2

Classes A class is a blueprint of an object It is the model or pattern from which objects are created A class defines the methods and types of data associated with an object Creating an object from a class is called instantiation; an object is an instance of a particular class For example, the Account class could describe many bank accounts, but toms_savings is a particular bank account with a particular balance 3

Creating Objects The new operator creates an object from a class: Account toms_savings = new Account (); This declaration asserts that toms_savings is a variable that refers to an object created from the Account class It is initialized to the object created by the new operator The newly created object is set up by a call to a constructor of the class 4

Constructors A constructor is a special method used to set up an object It has the same name as the class It can take parameters, which are often used to initialize some variables in the object For example, the Account constructor could be set up to take a parameter specifying its initial balance: Account toms_savings = new Account (125.89); 5

Object References The declaration of the object reference variable and the creation of the object can be separate activities: Account toms_savings; toms_savings = new Account (125.89); Once an object exists, its methods can be invoked using the dot operator: toms_savings.deposit (35.00); 6

The String Class A character string in Java is an object, defined by the String class String name = new String ("Ken Arnold"); Because strings are so common, Java allows an abbreviated syntax: String name = "Ken Arnold"; Java strings are immutable; once a string object has a value, it cannot be changed 7

The String Class A character in a string can be referred to by its position, or index The index of the first character is zero The String class is defined in the java.lang package (and is therefore automatically imported) Many helpful methods are defined in the String class See Carpe_Diem.java 8

The StringTokenizer Class The StringTokenizer class makes it easy to break up a string into pieces called tokens By default, the delimiters for the tokens are the space, tab, carriage return, and newline characters (white space) The StringTokenizer class is defined in the java.util package See Int_Reader.java 9

The Random Class A program may need to produce a random number The Random class provides methods to simulate a random number generator The nextint method returns a random number from the entire spectrum of int values Usually, the number must be scaled and shifted into a particular range to be useful See Flip.java 10

The Random Class Expression Range Math.abs (rand.newint()) % 6 + 1 Math.abs (rand.newint()) % 10 + 1 Math.abs (rand.newint()) % 101 Math.abs (rand.newint()) % 11 + 20 Math.abs (rand.newint()) % 11-5 1 to 6 1 to 10 0 to 100 20 to 30-5 to 5 11

References An object reference holds the memory address of an object Chess_Piece bishop1 = new Chess_Piece(); bishop1 All interaction with an object occurs through a reference variable References have an effect on actions such as assignment 12

Assignment The act of assignment takes a copy of a value and stores it in a variable For primitive types: num2 = num1; Before After num1 num2 num1 num2 5 12 5 5 13

Reference Assignment For object references, the value of the memory location is copied: bishop2 = bishop1; Before After bishop1 bishop2 bishop1 bishop2 14

Aliases Two or more references that refer to the same object are called aliases of each other There is only one copy of the object (and its data), but with multiple ways to access it Aliases can be useful, but should be managed carefully Affecting the object through one reference affects it for all aliases, because they refer to the same object 15

Garbage Collection When an object no longer has any valid references to it, it can no longer be accessed by the program It is useless, and therefore called garbage Java performs automatic garbage collection periodically, returning an object's memory to the system for future use In other languages, the programmer has the responsibility for performing garbage collection 16

Methods A class contains methods; prior to defining our own classes, we must explore method definitions We've defined the main method many times All methods follow the same syntax: return-type method-name ( parameter-list ) { statement-list } 17

Methods A method definition: int third_power (int number) { int cube; cube = number * number * number; return cube; } // method third_power 18

Methods A method may contain local declarations as well as executable statements Variables declared locally can only be used locally The third_power method could be written without any local variables: int third_power (int number) { return number * number * number; } // method third_power 19

The return Statement The return type of a method indicates the type of value that the method sends back to the calling location A method that does not return a value (such as main) has a void return type The return statement specifies the value that will be returned Its expression must conform to the return type 20

Method Flow of Control The main method is invoked by the system when you submit the bytecode to the interpreter Each method call returns to the place that called it main method1 method2 method1(); method2(); 21

Parameters A method can be defined to accept zero or more parameters Each parameter in the parameter list is specified by its type and name The parameters in the method definition are called formal parameters The values passed to a method when it is invoked are called actual parameters 22

Parameters When a parameter is passed, a copy of the value is made and assigned to the formal parameter Both primitive types and object references can be passed as parameters When an object reference is passed, the formal parameter becomes an alias of the actual parameter See Parameter_Passing.java Usually, we will avoid putting multiple methods in the class that contains the main method 23

Defining Classes The syntax for defining a class is: class class-name { declarations constructors methods } The variables, constructors, and methods of a class are generically called members of the class 24

Defining Classes class Account { int account_number; double balance; Account (int account, double initial) { account_number = account; balance = initial; } // constructor Account void deposit (double amount) { balance = balance + amount; } // method deposit } // class Account 25

Constructors A constructor: is a special method that is used to set up a newly created object often sets the initial values of variables has the same name as the class does not return a value has no return type, not even void The programmer does not have to define a constructor for a class 26

Classes and Objects A class defines the data types for an object, but a class does not store data values Each object has its own unique data space The variables defined in a class are called instance variables because each instance of the class has its own All methods in a class have access to all instance variables of the class Methods are shared among all objects of a class 27

Classes and Objects Objects account_number Class balance 2908371 573.21 int account_number double balance account_number 4113787 balance 9211.84 28

Encapsulation You can take one of two views of an object: internal - the structure of its data, the algorithms used by its methods external - the interaction of the object with other objects in the program From the external view, an object is an encapsulated entity, providing a set of specific services These services define the interface to the object 29

Encapsulation An object should be self-governing; any changes to the object's state (its variables) should be accomplished by that object's methods We should make it difficult, if not impossible, for another object to "reach in" and alter an object's state The user, or client, of an object can request its services, but it should not have to be aware of how those services are accomplished 30

Encapsulation An encapsulated object can be thought of as a black box; its inner workings are hidden to the client toms_savings deposit withdraw add_interest client produce_statement 31

Abstraction Encapsulation is a powerful abstraction An abstraction hides the right details at the right time We use abstractions every day: driving a car using a computer Encapsulation makes an object easy to manage mentally because its interaction with clients is limited to a set of well-defined services 32

Visibility Modifiers We accomplish encapsulation through the appropriate use of visibility modifiers A modifier is a Java reserved word that specifies particular characteristics of a programming construct We've used the modifier final to define a constant Java has three visibility modifiers: public, private, and protected We will discuss the protected modifier later 33

Visibility Modifiers Members of a class that are declared with public visibility can be accessed from anywhere Members of a class that are declared with private visibility can only be accessed from inside the class Members declared without a visibility modifier have default visibility and can be accessed by any class in the same package Java modifiers are discussed in detail in Appendix F 34

Visibility Modifiers As a general rule, no object's data should be declared with public visibility Methods that provide the object's services are usually declared with public visibility so that they can be invoked by clients Public methods are also called service methods Other methods, called support methods, can be defined that assist the service methods; they should not be declared with public visibility 35

Classes and Objects See Tunes.java music add_cds print main 36

The static Modifier The static modifier can be applied to variables or methods It associates a variable or method with the class rather than an object This approach is a distinct departure from the normal way of thinking about objects 37

Static Variables Normally, each object has its own data space If a variable is declared as static, only one copy of the variable exists for all objects of the class private static int count; Changing the value of a static variable in one object changes it for all others Static variables are sometimes called class variables 38

Static Methods Normally, we invoke a method through an instance (an object) of a class If a method is declared as static, it can be invoked through the class name; no object needs to exist For example, the Math class in the java.lang package contains several static mathematical operations Math.abs (num) -- absolute value Math.sqrt (num) -- square root 39

Static Methods The main method is static; it is invoked by the system without creating an object Static methods cannot reference instance variables, because instance variables don't exist until an object exists However, they can reference static variables or local variables Static methods are sometimes called class methods 40

Overloaded Methods Method overloading is the process of using the same method name for multiple methods The signature of each overloaded method must be unique The signature is based on the number, type, and order of the parameters The compiler must be able to determine which version of the method is being invoked by analyzing the parameters The return type of the method is not part of the signature 41

Overloaded Methods The println method is overloaded: println (String s) println (int i) println (double d) The lines etc. System.out.println ("The total is:"); System.out.println (total); invoke different versions of the println method 42

Overloaded Methods Constructors are often overloaded to provide multiple ways to set up a new object Account (int account) { account_number = account; balance = 0.0; } // constructor Account Account (int account, double initial) { account_number = account; balance = initial; } // constructor Account See Casino.java 43

Classes and Objects See Purchase_Power.java Manager name "Jim" Manager Purchase_Power name "Bob" jim bob Stock_Item name "beans" beans franks Stock_Item name "franks" product_buyer product_buyer 44

Classes and Objects See Storm.java current_size 4 Storm current_size 18 current_size 12 current_size 7 drop1 drop2 drop3 drop4 drop5 current_size 24 45