What will this print?

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

Creating and Using Objects

Encapsulation. Mason Vail Boise State University Computer Science

Anatomy of a Class Encapsulation Anatomy of a Method

Object Oriented Modeling

EECS168 Exam 3 Review

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

CSE115 Introduction to Computer Science I Coding Exercise #7 Retrospective Fall 2017

Chapter 4 Defining Classes I

Objects and Classes. Basic OO Principles. Classes in Java. Mark Allen Weiss Copyright 2000

Principles of Object Oriented Programming. Lecture 4

CS 101 Fall 2006 Midterm 3 Name: ID:

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

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

Chapter 4. Defining Classes I

CMSC131. Objects: Designing Classes and Creating Instances

CS1004: Intro to CS in Java, Spring 2005

The Object Oriented Paradigm

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

Warm-up: what does this print?

CLASSES AND OBJECTS IN JAVA

CS111: PROGRAMMING LANGUAGE II. Lecture 1: Introduction to classes

Object Oriented Programming in C#

TA office hours are over after this week, but Dan and Maja will still be around for the next month

Introduction to Classes and Objects. David Greenstein Monta Vista High School

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

COP 3330 Final Exam Review

Object Oriented Programming

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

CMPT 117: Tutorial 1. Craig Thompson. 12 January 2009

Object Oriented Programming COP3330 / CGS5409

Defining Classes. Chap 1 introduced many concepts informally, in this chapter we will be more formal in defining

ECE 122. Engineering Problem Solving with Java

Computer Science is...

STUDENT LESSON A5 Designing and Using Classes

Object Oriented Programming

Objects and Classes -- Introduction

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

Chapter 4: Writing Classes

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

Agenda: Notes on Chapter 3. Create a class with constructors and methods.

Implementing Classes

COMP-202: Foundations of Programming. Lecture 8: for Loops, Nested Loops and Arrays Jackie Cheung, Winter 2016

Implementing Classes (P1 2006/2007)

CMSC 132: Object-Oriented Programming II

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

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

Encapsulation in Java

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

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

BankAccount account1 = new BankAccount(...);,this

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

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

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

Java and OOP. Part 2 Classes and objects

Lecture 06: Classes and Objects

Dot and Scope Resolution Operator

Lecture 07: Object Encapsulation & References AITI Nigeria Summer 2012 University of Lagos.

ENGR 2710U Midterm Exam UOIT SOLUTION SHEET

UNIT 3 ARRAYS, RECURSION, AND COMPLEXITY CHAPTER 11 CLASSES CONTINUED

Classes and Methods: Classes

COMP 401: THE DUAL ROLE OF A CLASS. Instructor: Prasun Dewan (FB 150,

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

Object Oriented Design: Building a Fraction Class

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

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

CPS122 Lecture: Defining a Class

Object-Oriented Programming in Java

CS 251 Intermediate Programming Methods and Classes

About This Lecture. Data Abstraction - Interfaces and Implementations. Outline. Object Concepts. Object Class, Protocol and State.

CS 251 Intermediate Programming Methods and More

Inheritance (IS A Relationship)

The newest, most different stuff is Java variable declaration, array syntax, class instance syntax. Expect those to be emphasized.

CS112 Lecture: Defining Instantiable Classes

Programming Abstractions

Defining Classes and Methods

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

Recitation 3 Class and Objects

ASSIGNMENT 5 Objects, Files, and More Garage Management

Assignment 1 due Monday at 11:59pm

Classes as Blueprints: How to Define New Types of Objects

COMP 401 Spring 2014 Midterm 1

Introduction to Inheritance

Methods and Data (Savitch, Chapter 5)

Documenting, Using, and Testing Utility Classes

Today s Agenda. Quick Review

Software and Programming 1

COMP-202: Foundations of Programming. Lecture 10: Method Overloading and Passing Objects to Methods. Sandeep Manjanna, Summer 2015

An introduction to Java II

COMP 401 Spring 2013 Midterm 1

Understanding class definitions

CSE 331. Mutation and immutability

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

Questions Answer Key Questions Answer Key Questions Answer Key

Outline CSE 142. Specification vs Implementation - Review. CSE142 Wi03 F-1. Instance Variables

COMP-202 Unit 5: Basics of Using Objects

CSE 373. Objects in Collections: Object; equals; compareto; mutability. slides created by Marty Stepp

Programming Languages and Techniques (CIS120)

Logistics. Final Exam on Friday at 3pm in CHEM 102

CHAPTER 7 OBJECTS AND CLASSES

Transcription:

class UselessObject{ What will this print? int evennumber; int oddnumber; public int getsum(){ int evennumber = 5; return evennumber + oddnumber; public static void main(string[] args){ UselessObject a = new UselessObject(); UselessObject b = new UselessObject(); a.evennumber = 2; System.out.println(a.getSum() - b.getsum()); 1

0 2

Scope: summary so far The fields of a class A are visible everywhere inside A. You can only define block scope with { inside methods. Local variables and formal parameters are visible everywhere inside the method they're defined in, unless they're defined in a block. Local variables and formal parameters can hide class fields. 3

class MoreScope{ int j = 1; int i = 3; public int foo(int x){ int i = 2; int k = 3; { int j = 3; k = i + j + x; return k; int y = 0; public int bar(int i){ return y + i * 2; What does this print? public int foobar(){ return foo(5) + bar(1); public static void main(string [] args){ MoreScope x = new MoreScope(); System.out.println(x.foobar()); 4

10 5

class MoreScope{ int j = 1; int i = 3; public int foo(int x){ int i = 2; int k = 3; { int j = 3; k = i + j + x; return k; int y = 0; public int bar(int i){ return y + i * 2; public int foobar(){ return foo(5) + bar(1); // foo(5) is 8, and bar(1) is 2 public static void main(string [] args){ MoreScope x = new MoreScope(); System.out.println(x.foobar()); 6

COMP 202 Introduction to Computing 1 Access Modifiers 7

Terminology: class member Class member: any field or method defined in class A is a class member of A. Instance variables (fields) Static variables (fields) Instance methods Static methods 8

Access Modifiers (public/private) COMP 202 Introduction to Computing 1 When declaring a member of a class (methods and variables), we can use an access modifier (or visibility modifier) Access modifiers affect scope: they are used to control which methods can refer to certain members of a class 9

Access Modifiers: Account Class COMP 202 Introduction to Computing 1 public class Account { private int number; private double balance; private boolean status; public Account(int accountnumber) { /*... */ public int getnumber() { /*... */ public double getbalance() { /*... */ public boolean isopen() { /*... */ public void deposit(double amount) { /*... */ public boolean withdraw(double amount) { /*... */ public boolean close() { /*... */ 10

Access modifiers So far, we've only been using the public access modifier. In many of my examples, I used no access modifier at all (Bad Maja!): don't do this any code you write for this course! Now we introduce the private modifier. 11

Access Modifiers COMP 202 Introduction to Computing 1 When a member is public, you can refer to it in any method defined in any class using the. (dot) operator When a member is private, you can refer to it only in methods that are defined in the same class 12

Access Modifiers (Warning) COMP 202 Introduction to Computing 1 Note that if you do not explicitly declare an access modifier, the default is an access modifier that is neither public nor private 13

class Fraction { public int numerator; public int denominator; public boolean ispositive; public Fraction(int top, int bottom){ numerator = top; denominator = bottom; int product = top * bottom; ispositive = true; if(product < 0) ispositive = false; public int getnumerator(){ return numerator; Redundant methods, because numerator and denominator can be accessed with dot operator from anywhere. public int getdenominator(){ return denominator; 14

class Fraction { private int numerator; private int denominator; private boolean ispositive; public Fraction(int top, int bottom){ numerator = top; denominator = bottom; int product = top * bottom; ispositive = true; if(product < 0) ispositive = false; public int getnumerator(){ return numerator; public int getdenominator(){ return denominator; Now these methods are necessary because numerator and denominator cannot be accessed with dot operator from anywhere except inside the Fraction class. 15

class Fraction { private int numerator; private int denominator; private boolean ispositive; public Fraction(int top, int bottom){ numerator = top; denominator = bottom; int product = top * bottom; ispositive = true; if(product < 0) ispositive = false; private int getnumerator(){ return numerator; private int getdenominator(){ return denominator; Now there's no way to access numerator and denominator from outside of the Fraction class. These two methods are once again redundant. 16

class Fraction { private int numerator; private int denominator; private boolean ispositive; public Fraction(int top, int bottom){ numerator = top; denominator = bottom; int product = top * bottom; ispositive = true; if(product < 0) ispositive = false; private int getnumerator(){ return numerator; private int getdenominator(){ return denominator; These are accessor methods. We need to write mutator methods if we want to be able to change the values of these variables from outside Fraction. 17

Exercise 18

Encapsulation COMP 202 Introduction to Computing 1 Accessing instance variables directly (or enabling direct access to instance variables) is dangerous and considered bad practice Most instance variables should only be accessible via accessor and mutator methods (like It ensures that programmers who use the classes you write can only access instance variables in ways you control In order to protect against direct access: Instance variables should be private All access and modifications to variables should be done via accessor and mutator methods 19

Reread the ACCESS MODIFIERS AND SCOPE section in General Instructions and Regulations for Assignments 20

private vs. public Methods COMP 202 Introduction to Computing 1 Methods that are to be publicly accessible should be public They are the interface with which objects of the class can be accessed and manipulated We might have some helper methods used internally These methods support other methods in the class (other methods in the class call them) They should be declared private 21

From Unit 5: Method Overloading (Useful for A4) COMP 202 Introduction to Computing 1 Method overloading is the process of using the same method name for multiple methods declared in the same class 22

Overloading Example (1) COMP 202 Introduction to Computing 1 Consider the following class definition: public class OverloadingDemo { public static double tryme(int x) { return x + 0.375; public static double tryme(int x, double y) { return x * y; public static void main(string[] args) { double result = tryme(25, 4.32); System.out.println(result);

More Overloading Examples COMP 202 Introduction to Computing 1 Many methods defined in the Java Class Library are overloaded The following lines invoke different versions of the println() method: System.out.println("The total is: "); System.out.println(total); 24

Constructors can also be overloaded COMP 202 Introduction to Computing 1 public class Account { // Member variable declarations public Account(int accountnumber, String ownername) { number = accountnumber; balance = 0.0; status = true; owner = ownername; public Account(int accountnumber, String ownername, double initialamount) { number = accountnumber; balance = initialamount; status = true; owner = ownername; // Other declarations 25

Summary COMP 202 Introduction to Computing 1 By now, you should understand the scope rules for formal method parameters, local method variables and class fields. Access modifiers (public/private) affect the scope of class fields and methods. Access modifiers provide programmers with control over how a class can be used by external parties very important for program design. Reread the General Instructions and Regulations for Assignments, so you know which rules to follow for A4. Assignment 4 will be using method/constructor overloading: review the relevant material from Unit 5. 26

Old Exam Question Using the documentation for the ArrayList class, try the exam question posted on the discussion board under WordSet - Nov 8 lecture, Section 1 under Resources. We'll go over it next class (on Wednesday). 27

Write a class called WordSet representing a set of String objects which can contain an arbitrary number of Strings, limited only by the memory available to the Java Virtual Machine. A set is a collection of elements; however, unlike a list, a set cannot contain duplicate elements. Therefore, as its name implies, a WordSet object cannot contain duplicate Strings; that is, if one attempts to add a String to a WordSet, and the WordSet already contains an element which is equal to this String, the attempt will fail and the state of the WordSet will not change. All String comparisons performed in the methods defined in the WordSet class are done in a case-sensitive manner. 28