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

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

Anatomy of a Class Encapsulation Anatomy of a Method

Chapter 4: Writing Classes

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

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

Objects and Classes -- Introduction

COMP 202. Building Your Own Classes. CONTENTS: Anatomy of a class Constructors and Methods (parameter passing) COMP 202 Objects 2 1

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

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

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

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

ECE 122. Engineering Problem Solving with Java

COMP 202. Building Your Own Classes. CONTENTS: Anatomy of a class Constructors and Methods (parameter passing) Instance Data. COMP Objects 2 1

Lecture 5: Methods CS2301

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

Chapter 5: Writing Classes and Enums

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

ECE 122. Engineering Problem Solving with Java

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

Where do objects come from? Good question!

CS1004: Intro to CS in Java, Spring 2005

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

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

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

Object-Oriented Design. Chapter

Chapter. We've been using predefined classes. Now we will learn to write our own classes to define objects

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

Chapter 4 Defining Classes I

Announcements. PS 3 is due Thursday, 10/6. Midterm Exam 1: 10/14 (Fri), 9:00am-10:53am

Opening Problem. Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively.

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

ECE 122. Engineering Problem Solving with Java

COSC 111: Computer Programming I. Dr. Bowen Hui University of Bri>sh Columbia Okanagan

Opening Problem. Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively.

CS1004: Intro to CS in Java, Spring 2005

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

Object-Oriented Programming Concepts

Designing Classes part 2

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

Java Object Oriented Design. CSC207 Fall 2014

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

CS110D: PROGRAMMING LANGUAGE I

Container Vs. Definition Classes. Container Class

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

CS 251 Intermediate Programming Methods and Classes

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

Chapter 7 User-Defined Methods. Chapter Objectives

COMP 202 Java in one week

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods

writing classes objectives chapter

Building Your Own Classes

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

Questions Answer Key Questions Answer Key Questions Answer Key

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

CS 251 Intermediate Programming Methods and More

What will this print?

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

Programming by Delegation

COMP 202. Java in one week

Object Oriented Programming in C#

Chapter 6 Introduction to Defining Classes

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

Lecture #6-7 Methods

Chapter 2: Data and Expressions

Assignment 1 due Monday at 11:59pm

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

Conditional Execution

To define methods, invoke methods, and pass arguments to a method ( ). To develop reusable code that is modular, easy-toread, easy-to-debug,

JAVA GUI PROGRAMMING REVISION TOUR III

Programming: Java. Chapter Objectives. Chapter Objectives (continued) Program Design Including Data Structures. Chapter 7: User-Defined Methods

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

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

Recitation 02/02/07 Defining Classes and Methods. Chapter 4

CS1083 Week 2: Arrays, ArrayList

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

Packages & Random and Math Classes

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

Design Patterns: State, Bridge, Visitor

CS115 Principles of Computer Science

Chapter 8 Objects and Classes Dr. Essam Halim Date: Page 1

Week 6 CS 302. Jim Williams, PhD

CS121: Computer Programming I

This Week s Agenda (Part A) CS121: Computer Programming I. Changing Between Loops. Things to do in-between Classes. Answer. Combining Statements

Methods. CSE 114, Computer Science 1 Stony Brook University

Chapter 5 Methods. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

Object Oriented Modeling

BİLGE KÖROĞLU. Lecture Notes (May 2 4, 2007) METHOD DECOMPOSITION and ARRAYS

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

1 class Lecture2 { 2 3 "Elementray Programming" / References 8 [1] Ch. 2 in YDL 9 [2] Ch. 2 and 3 in Sharan 10 [3] Ch.

Chapter 6 Methods. Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited

Selected Questions from by Nageshwara Rao

Method OverLoading printf method Arrays Declaring and Using Arrays Arrays of Objects Array as Parameters

Methods and Data (Savitch, Chapter 5)

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled

Classes and Objects 3/28/2017. How can multiple methods within a Java class read and write the same variable?

1 class Lecture5 { 2 3 "Methods" / References 8 [1] Ch. 5 in YDL 9 [1] Ch. 20 in YDL 0 / Zheng-Liang Lu Java Programming 176 / 199

Object Communication

Lecture 02, Fall 2018 Friday September 7

Lecture 04 FUNCTIONS AND ARRAYS

Transcription:

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 An object is an abstraction, hiding details from the rest of the system COMP 202 - Week 4 1

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 one object to "reach in" and alter another 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 COMP 202 - Week 4 2

Encapsulation An encapsulated object can be thought of as a black box Its inner workings are hidden to the client, which only invokes the interface methods Client Methods Data COMP 202 - Week 4 3

Visibility Modifiers In Java, we accomplish encapsulation through the appropriate use of visibility modifiers A modifier is a Java reserved word that specifies particular characteristics of a method or data value 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 COMP 202 - Week 4 4

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 E COMP 202 - Week 4 5

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 A method created simply to assist a service method is called a support method Since a support method is not intended to be called by a client, it should not be declared with public visibility COMP 202 - Week 4 6

Method Declarations Revisited A method declaration begins with a method header char calc (int num1, int num2, String message) return type method name parameter list The parameter list specifies the type and name of each parameter The name of a parameter in the method declaration is called a formal parameter COMP 202 - Week 4 7

Method Declarations The method header is followed by the method body char calc (int num1, int num2, String message) { int sum = num1 + num2; char result = message.charat (sum); } return result; The return expression must be consistent with the return type sum and result are local data They are created each time the method is called, and are destroyed when it finishes executing COMP 202 - Week 4 8

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 has a void return type The return statement specifies the value that will be returned Its expression must conform to the return type COMP 202 - Week 4 9

Parameters Each time a method is called, the actual parameters in the invocation are copied into the formal parameters ch = obj.calc (25, count, "Hello"); char calc (int num1, int num2, String message) { int sum = num1 + num2; char result = message.charat (sum); } return result; COMP 202 - Week 4 10

Constructors Revisited Recall that a constructor is a special method that is used to set up a newly created object When writing a constructor, remember that: it has the same name as the class it does not return a value it has no return type, not even void it often sets the initial values of instance variables The programmer does not have to define a constructor for a class See SuperCat.java See FeedTheCats.java See BankAccounts.java See Account.java COMP 202 - Week 4 11

COMP 202 Week 4 cont d We ve seen how to write basic classes and create objects. Next, we will examine particular relationships between objects, how to associate variables and methods with the class itself (rather than with an object of the class), and revisit methods in more detail. This module focuses on: Object relationships: aggregation (the ''has-a'' relation) Static members (variables & methods) Method decomposition Method overloading COMP 202 - Week 4 12

An aggregate Bus object An aggregate object is an object that contains references to other objects An aggregate object represents a has-a relationship. A bus has a maximum speed, a number of seats, and a number of passengers. A bus also has a driver. A bus can travel, pick up passengers, drop off passengers, and change drivers. see Bus.java A driver has a name, an age, and a risk-taking factor. A driver can accept or refuse a passenger, and may fall asleep at the wheel. see Driver.java, QuebecBusTour.java COMP 202 - Week 4 13

Writing Classes Sometimes an object has to interact with other objects of the same type For example, we might add two Rational number objects together as follows: r3 = r1.add(r2); One object (r1) is executing the method and another (r2) is passed as a parameter See RationalNumbers.java See Rational.java COMP 202 - Week 4 14

The static Modifier The static modifier can be applied to variables as well as methods It associates a variable or method with the class rather than an object To make a variable or method static, we apply the static modifier to the declaration Invoked through the class name rather than through a particular object COMP 202 - Week 4 15

Class Variables Static variables are sometimes called class variables Normally, each object has its own data space If a variable is declared as static, only one copy of the variable exists, ex: private static float amount; public static final double PI = 3.14159; public static int numcircles; Memory space for a static variable is created as soon as the class in which it is declared is loaded Can be used always, even if class is never instantiated. To access class variables, use the class name. COMP 202 - Week 4 16

Class Variables All objects created from the class share access to the static variable Changing the value of a static variable in one object changes it for all others Static methods and variables often work together See TheProudMotherCat.java See Cat.java COMP 202 - Week 4 17

class SphereArea Class Methods public static final float PI=3.14159; public static float area(float rad); { return( 4 * PI * rad * rad ); } class SphereTest public static void main(string args[]) { Scanner scan = new Scanner(System.in); System.out.println("Enter radius of sphere: "); float radius = scan.nextfloat(); float area = SphereArea.area(radius); System.out.println("Area of sphere is " + area); } COMP 202 - Week 4 18

public class SphereArea { Class Methods static final float PI=3.14159; public static void main(string args[]) { Scanner scan = new Scanner(System.in); System.out.println("Enter radius of sphere: "); float radius = scan.nextfloat(); System.out.println("Area of sphere is" + area(radius) ); } } public static float area(float rad); { return( 4 * PI * rad * rad ); } COMP 202 - Week 4 19

Class Methods The order of the modifiers can be interchanged, but by convention visibility modifiers come first Recall that 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 COMP 202 - Week 4 20

Class Methods Equivalent to global methods, but no danger of name conflicts. Very similar to Class variables. Math and System are classes that only defines class methods because there is no appropriate object framework. Example: Math.sqrt(i); Math is the name of the class, and sqrt() is the name of class method (or static method). COMP 202 - Week 4 21

Reduce complexity Abstraction Java Methods Revisited hide information so that you won't need to think about it Minimize code size Improve maintainability and correctness Avoid duplicate code Limit effect of changes Hide the order in which events happen to be processed Improve performance Promote code reuse Make a section of code readable (short functions valuable) COMP 202 - Week 4 22

Method Decomposition A method should be relatively small, so that it can be readily understood as a single entity A potentially large method should be decomposed into several smaller methods as needed for clarity Therefore, a service method of an object may call one or more support methods to accomplish its goal See PigLatin.java See PigLatinTranslator.java COMP 202 - Week 4 23

Overloading 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 includes 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 COMP 202 - Week 4 24

Overloading Methods Version 1 float tryme (int x) { return x +.375; } Version 2 float tryme (int x, float y) { return x*y; } Invocation result = tryme (25, 4.32) COMP 202 - Week 4 25

Overloaded Methods The println method is overloaded: println (String s) println (int i) println (double d) etc. The following lines invoke different versions of the println method: System.out.println ("The total is:"); System.out.println (total); COMP 202 - Week 4 26

Overloading Methods Constructors can be overloaded An overloaded constructor provides multiple ways to set up a new object See SnakeEyes.java See Die.java See SimpleCat.java COMP 202 - Week 4 27