Classes & Objects CMSC 202

Similar documents
Encapsula)on CMSC 202

Sept 26, 2016 Sprenkle - CSCI Documentation is a love letter that you write to your future self. Damian Conway

Object Oriented Design (OOD): The Concept

A Founda4on for Programming

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

Ch. 6. User-Defined Methods

BBM 102 Introduc0on to Programming II Spring 2014

Condi(onals and Loops

Object Oriented Programming. Feb 2015

Mo#va#ng the OO Way. COMP 401, Fall 2017 Lecture 05

Learning objec<ves. Classes, Objects, and Methods. Problem Decomposi<on. Problem Decomposi<on (cont d)

NAMES, SCOPES AND BINDING A REVIEW OF THE CONCEPTS

Classes and objects. Chapter 2: Head First Java: 2 nd Edi4on, K. Sierra, B. Bates

Programming Languages and Techniques (CIS120)

method method public class Temperature { public static void main(string[] args) { // your code here } new

Garbage collec,on Parameter passing in Java. Sept 21, 2016 Sprenkle - CSCI Assignment 2 Review. public Assign2(int par) { onevar = par; }

Documen(ng code, Javadoc, Defensive Programming, Asserts, Excep(ons & Try/Catch

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and More

Methods. Methods. Mysteries Revealed

10/7/15. MediaItem tostring Method. Objec,ves. Using booleans in if statements. Review. Javadoc Guidelines

History of Java. Java was originally developed by Sun Microsystems star:ng in This language was ini:ally called Oak Renamed Java in 1995

PROGRAMMING FUNDAMENTALS

Proofs about Programs

Agenda. Excep,ons Object oriented Python Library demo: xml rpc

Fundamentals of Programming Data Types & Methods

more uml: sequence & use case diagrams

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

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

Java Basics. Object Orientated Programming in Java. Benjamin Kenwright

Introduc)on to Classes and Objects. Dr. Bowen Hui Computer Science University of Bri)sh Columbia Okanagan

Arrays. Eng. Mohammed Abdualal

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

CSIS 10A Assignment 9 Solutions

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program:

Programming Languages and Techniques (CIS120)

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

Lecture 2: Java & Javadoc

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

Func%onal Programming in Scheme and Lisp

CS 1331 Exam 1. Fall Failure to properly fill in the information on this page will result in a deduction of up to 5 points from your exam score.

Ø Interface methods are public by default

CS101: Fundamentals of Computer Programming. Dr. Tejada www-bcf.usc.edu/~stejada Week 1 Basic Elements of C++

Func%onal Programming in Scheme and Lisp

Using APIs. Chapter 3. Outline Fields Overall Layout. Java By Abstraction Chapter 3. Field Summary static double PI

Lecture 5: Methods CS2301

A Func'onal Introduc'on. COS 326 David Walker Princeton University

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

Topics. The Development Process

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program:

CMSC201 Computer Science I for Majors

Array Basics: Outline

Java objects: a first view [Reading: chapters 1 & 2] CSC 142 B 1

Strings, Arrays, A1. COMP 401, Spring 2015 Lecture 4 1/20/2015

CS 1331 Exam 1 ANSWER KEY

University of Cape Town ~ Department of Computer Science Computer Science 1015F ~ Test 2. Question Max Mark Internal External

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

Object Oriented Programming

Recitation 3 Class and Objects

Example Program. public class ComputeArea {

Chapter 4 Defining Classes I

CS 211: Existing Classes in the Java Library

(Func&onal (Programming (in (Scheme)))) Jianguo Lu

Object Oriented Programming. Java-Lecture 6 - Arrays

Func+on applica+ons (calls, invoca+ons)

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

JAVA: A Primer. By: Amrita Rajagopal

COMP 110 Introduction to Programming. What did we discuss?

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Chapter 5 Lab Methods

S <: T Type compa*bility rela*on.

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

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

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Object Oriented Programming

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

Declaring and ini,alizing 2D arrays

Programming in the Large II: Objects and Classes (Part 2)

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

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

Programming Languages and Techniques (CIS120)

CS111: PROGRAMMING LANGUAGE II

Objec+ves. Review. Basics of Java Syntax Java fundamentals. What are quali+es of good sooware? What is Java? How do you compile a Java program?

MIDTERM REVIEW. midterminformation.htm

Object-Oriented Programming Concepts

Architectural Requirements Phase. See Sommerville Chapters 11, 12, 13, 14, 18.2

Lecture Notes CPSC 224 (Spring 2012) Today... Java basics. S. Bowers 1 of 8

Chapter 6 Lab Classes and Objects

Chapter 6 Lab Classes and Objects

Midterm Examination (MTA)

Programming Languages and Techniques (CIS120e)

Darrell Bethea May 20, 2011

CS171:Introduction to Computer Science II

Principles of Programming Languages

Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming

For example, when we first started Java programming we described the HelloWorld class:

CS 101 Spring 2007 Midterm 2 Name: ID:

Objects and Classes Lecture 2

Data Types. 1 You cannot change the type of the variable after declaration. Zheng-Liang Lu Java Programming 52 / 87

CLASSES AND OBJECTS. Fundamentals of Computer Science I

Transcription:

Classes & Objects CMSC 202

Programming & Abstrac9on All programming languages provide some form of abstrac'on Also called informa'on hiding Separa9ng how one uses a program and how the program has been implemented Procedural Programming Data Abstrac9on using data structures Control Abstrac9on using func9ons Object Oriented Languages Data and Control Abstrac9on uses classes

Procedural vs. Object Oriented Procedural Calculate the area of a circle given the specified radius Sort this class list given an array of students Calculate the student s GPA given a list of courses Object Oriented Circle, what s your radius Class list, sort students Transcript, what s the student s GPA

What is a Class? From the Dic9onary A kind or category A set, collec9on, group, or configura9on containing members regarded as having certain a3ributes or traits in common From an Object Oriented Perspec9ve A group of objects with similar proper'es, common behavior, common rela'onships with other objects, and common seman'cs We use classes for abstrac'on purposes

Classes Classes are blueprints for crea9ng a group of objects Classes of birds Classes of cars Classes of shoes The blueprint defines The class s behavior as methods The class s state/arributes as variables

Class or Object? Variables of class types may be created just like variables of built- in types Using a set of blueprints you could create a bakery You can create as many instances of the class type as you like There is more than one bakery in Bal9more The challenge is to define classes and create objects that sa9sfy the problem Do we need an Oven class?

Class Interface The requests you can make of an object are determined by its interface Do we need to know how bagels are made in order to buy one? All we actually need to know is which bakery to go to and what ac9on we want to perform Bakery Class Is the bakery open/closed? Buy bread Buy bagel Buy muffin Buy coffee Type Interface

Implementa9on Code and hidden data in the class that sa9sfies requests make up the class's implementa'on What s hidden in a bakery? Every request made of an object must have an associated method that will be called In OO- speak we say that you are sending a message to the object, which responds to the message by execu9ng the appropriate code

Class Defini9ons We ve already seen... How to use classes and the objects created from them... Scanner input = new Scanner(System.in); How to invoke their methods using the dot nota9on int num = input.nextint(); Let us add onto what we already know

Class Defini9on A class defini'on defines the class blueprint The behaviors/services/ac9ons/opera9ons of a class are implemented methods Also known as member func'ons The state of the class is stored in its members Also known as fields, a3ributes, or instance variables A challenging aspect of OOP is determining what classes get modeled and at what level of detail This answer will vary based on the problem at hand

Objects Remember an object is a par9cular instance of an a class As such, all objects have Members The variable types and names (same across all instances) The members of each object can hold different values (unique to that instance) The state of an object is defined by these values Methods The tasks that the object can perform (same across all instances)

Anatomy of a Java Class Access modifier (more on this later) Keyword class Name of the class public class Bakery { Class body: members, methods NO semi- colon (c++)

Members Objects store their individual states in non- sta9c fields known as members Primi9ve types or reference types Accessible by all methods of the class Thus the members are said to have class scope Members are referenced using the dot operator numitems = array.length;

Anatomy of Class Members public class Bakery { Op9onal access modifier (more on this later) Member type Member name public boolean closed ; int numbagels ; + Remaining class body (methods)

Car Example What characteris9cs (members) are necessary to store the state for a Car? public class Car { int horsepower; int numdoors; int year; String vin; String color; String model; String make; //...

Methods Objects are sent messages which in turn call methods Methods may be passed arguments and may return something as well Methods are available to instances of the class Like members, methods are also referenced using the dot operator System.out.println(name.charAt(0));

Anatomy of a Method Op9onal access modifier (More on this later) return type (may be void) Name of method Op9onal parameters public int getbagelcount { () Method code: local variables and statements

Car Example What services/behaviors might be appropriate for a Car? public class Car { //... void unlockdoors() { /*... */ void changecolor(string color) { /*... */ void changegear(char gear) { /*... */ boolean isparkingbrakeengaged() { /*... */ void engageparkingbrake() { /*... */ void disengageparkingbrake() { /*... */ void depressaccelerator(float percentage) { /*... */ void depressbrake(float percentage) { /*... */ //...

Crea9ng a Car The following defines a variable of type Car However there is no Car object yet! Car mycar; The statement mycar = new Car( ) creates a new Car object and associates it with the variable mycar Now mycar refers to a Car object mycar = new Car(); For convenience, these statements can be (and are typically) combined Car mycar = new Car();

Car Example public static void main(string args[]) { Car mycar = new Car(); mycar.vin = "123567890ABCDEF"; mycar.numliters = 2; mycar.horsepower = 195; mycar.year = 2008; mycar.changecolor("black"); System.out.println("Car is colored: " + mycar.color); System.out.println("Car is " + (2011 - mycar.year) + " years old");

Pain9ng the Car We can change the state of any Car through services defined in the class defini9on public void changecolor(string color){ color = color; Which color are we referring to? The compiler assumes that all uses of color refer to the method parameter and hence this code has no effect // change car color mycar.changecolor("blue"); System.out.println(myCar.color);

The Calling Object Within a method, a variable is reconciled in a specific order 1. The parameter list is checked for a variable with that name 2. The class s members are checked to see if there s a match What we re really looking for is something to refer to the calling object public void setcolor(string color) { "calling object".color = color; In Java, the reserved word this represents the calling object It is some9mes necessary to iden9fy the calling object It is also a marer of style public void setcolor(string color) { this.color = color;

Prin9ng an Object If you print you class by passing it to System.out.println(), you ll get some cryp9c looking output like so Car@54fc9944 The print methods will u9lize a method called tostring() to format the output if you ve implemented it It s usually a good idea to implement this method so you can easily see the state of your objects public String tostring() {! "String state = "";! "state += "make: " + make;! "state += " model: " + model;! "//...! "return state;!

Object Equality Reference type variables cannot be tested for equality using the == operator Tes9ng 2 reference types for equality will resul9ng in comparing the underlying addresses public static void main(string[] args){ Car car1 = new Car(); Car car2 = new Car(); // customize both cars if(car1 == car2){ System.out.println("Same Car"); else{ System.out.println("Different Cars"); FF00 Car car1 FF20 Car car2

.equals() To actually compare the state of two objects we must implement a.equals() method public boolean equals(car othercar){ if(horsepower!= othercar.horsepower){ return false; if(!make.equals(othercar.make)){ return false; //... compare necessary members... // otherwise, if all equal return true return true; Notes: Returns a boolean Compares only Cars as implemented Defini9on of what cons9tutes equals may vary class to class

Class & Method Documenta9on Class & method level documenta9on is intended for the consumer of the class it serves to help the user Determine if the class is useful/applicable to their problem Find the appropriate method(s) and use them correctly Class comments High level documenta9on as to what the class represents and does Method comments important to explain What the method does What the method takes as arguments What it returns

Pre- condi9ons & Post- condi9ons Pre and Post- condi9ons are important to document in the method comments Pre- condi9ons All assump9ons made about func9onal parameters and the state of the calling object For example: the parameter mileage is expected to be non- nega9ve Post- condi9ons All assump9ons a user can make aper the execu9on For example: upon successful comple9on the car will have a new paint color

Javadocs Java provides API documenta9on (known as javadocs) for the built- in class library The documenta9on for each class contains this class and method level documenta9on Found online (e.g. String, Math, Scanner) These docs are created using the javadoc tool Required for CMSC 202 Project Documenta9on Demonstrated in Lab 01

Javadoc Format Free- form text to describe method @param tag to iden9ty and describe parameters You should have a @param tag for each argument @return tag to detail what s returned when called /** * <description of what the method does> * * @param arg1 <description of arg1> * @param arg2 <description of arg2> * @return <description of what's returned> */ <return type> methodname(<type 1> arg1, <type 2> arg2) { // method body

Example Javadoc /** * Changes the color of the calling object's color variable * * @param color a color that is real to change the car's color to * @return the old color of the car */ public String changecolor(string color){ String old = this.color; this.color = color; return old;