F II 3. Classes and Objects Objectives

Slides:



Advertisements
Similar presentations
SOFTWARE AND PROGRAMMING 1 Lecture 3: Ticketing machine: Constructor, method, menu Instructor: Prof. Boris Mirkin web-site
Advertisements

Understanding class definitions Looking inside classes 5.0.
Looking inside classes Fields, Constructors & Methods Week 3.
Looking inside classes Choices Week 4. Class bodies contain fields, constructors and methods. Fields store values that determine an object’s state. Constructors.
ISBN Chapter 11 Abstract Data Types and Encapsulation Concepts.
Understanding class definitions Looking inside classes 3.0.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
Understanding class definitions – Part II –. Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Main.
Abstract data types & object-oriented paradigm. Abstraction Abstraction: a view of an entity that includes only the attributes of significance in a particular.
Lecture 9 Concepts of Programming Languages
1 Reflecting on the ticket machines Their behavior is inadequate in several ways: –No checks on the amounts entered. –No refunds. –No checks for a sensible.
Understanding class definitions Looking inside classes.
Programming in Java; Instructor:Moorthy Introduction, Objects, Classes, Libraries1 Programming in Java Introduction.
Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
Programming Languages and Paradigms Object-Oriented Programming.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 2.
Introduction to Java. 2 Textbook David J. Barnes & Michael Kölling Objects First with Java A Practical Introduction using BlueJ Fourth edition, Pearson.
Classes CS 21a: Introduction to Computing I First Semester,
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
SOFTWARE AND PROGRAMMING 1 In-class open-book TEST1 on 6/02 Lab SH131: Ms Mihaela Cocea (from ) Room London Knowledge Lab Emerald.
SOFTWARE AND PROGRAMMING 1 Lecture: MB33 7:30-9:00 (except 11& ) Lab: B43, MB321, MB536 6:00-7:30 (from ) [each student must have obtained.
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
1 CSC 222: Object-Oriented Programming Spring 2013 Understanding class definitions  class structure  fields, constructors, methods  parameters  assignment.
Chapter 8 Objects and Classes Object Oriented programming Instructor: Dr. Essam H. Houssein.
Chapter 10 Defining Classes. The Internal Structure of Classes and Objects Object – collection of data and operations, in which the data can be accessed.
Understanding class definitions
1 COS 260 DAY 3 Tony Gauvin. 2 Agenda Questions? 1 st Mini quiz on chap1 terms and concepts –Today In BlackBoard –30 min., M/C and short answer, open.
Object-Oriented Programming Simple Stack Implementation.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
ISBN Chapter 11 Abstract Data Types and Encapsulation Concepts.
1 Opbygning af en Java klasse Abstraktion og modularisering Object interaktion Introduktion til Eclipse Java kursus dag 2.
Copyright by Scott GrissomCh 2 Class Definition Slide 1 Class Structure public class BankAccount{ fields constructor(s) methods } Sample Code Ticket Machine.
Looking inside classes Conditional Statements Week 4.
Object Oriented Programming and Data Abstraction Rowan University Earl Huff.
AP Java Ch. 4 Review Question 1  Java methods can return only primitive types (int, double, boolean, etc).
Java: Variables and Methods By Joshua Li Created for the allAboutJavaClasses wikispace.
Structured Programming Dr. Atif Alhejali Lecture 4 Modifiers Parameters passing 1Structured Programming.
Object-Oriented Programming in Java. 2 CS2336: Object-Oriented Programming in Java Buzzwords interfacejavadoc encapsulation coupling cohesion polymorphic.
1 Lecture # 2. * Introducing Programming with an Example * Identifiers, Variables, and Constants * Primitive Data Types * Byte, short, int, long, float,
Understanding class definitions Exploring source code 6.0.
SOFTWARE AND PROGRAMMING 1 Advert : NO TEST1 on 7/02: TEST1 will be 14/02 Lab: SH131, BBK536 6:00-7:30 (from ) [each student must have obtained.
SOFTWARE AND PROGRAMMING 1
CSC 222: Object-Oriented Programming Fall 2015
Class definitions CITS1001 week 2.
Introduction to Classes and Objects
Abstract Data Types and Encapsulation Concepts
Yanal Alahmad Java Workshop Yanal Alahmad
Understanding class definitions
Lecture 9 Concepts of Programming Languages
public class BankAccount{
Understanding class definitions
Chapter 3 Introduction to Classes, Objects Methods and Strings
Chapter 3 Introduction to Classes, Objects Methods and Strings
Abstract Data Types and Encapsulation Concepts
COS 260 DAY 3 Tony Gauvin.
CS100J Lecture 7 Previous Lecture This Lecture Java Constructs
Understanding class definitions
COS 260 DAY 4 Tony Gauvin.
JAVA CLASSES.
Object Oriented Programming in java
Classes CS 21a: Introduction to Computing I
CS 1054: Lecture 2, Chapter 1 Objects and Classes.
Arrays Arrays are represented by objects but there is no class that array objects are instances of. Variables of array type are declared using bracket.
Corresponds with Chapter 5
Chapter 7 Objects and Classes
Lecture 9 Concepts of Programming Languages
Coming up Variables Quick look at scope Primitives Objects
Presentation transcript:

242-210 F II 3. Classes and Objects Objectives explain classes and objects introduce fields, constructors, and methods go through two examples Original Slides by Dr. Andrew Davison

Topics 1. What are Classes, Objects? 2. The Contents of a Class 3. A Stack Class 4. Creating a Stack Object 5. Understanding a Stack Object 6. A Bad Stack Interface 7. Good vs. Bad Interfaces 8. Creating Two Stack Objects 9. Object Types vs. Primitive Types 10. A Ticket Machine

1. What are Classes, Objects? A class is a factory for objects. e.g. a Car class is a factory for Car objects A Car class is not a Car object e.g. a Car factory is not the Cars it makes Car class Car objects

Very Important Slide A class consists of data (fields) and methods. Each object gets a copy of the class's data (fields). An object uses the methods stored in the class the class is a kind of method library for all of its objects

A Class Involves at least 2 People A class is implemented by one person. A class is used by other, different people. The implementor wants to make a class that is easy to use. A user does not care how a class is implemented. He only wants to know the operations that it can carry out (its interface).

A Class for a Stack pop push Other operations: is Empty topOf A Stack (of plates) This interface helps the implementor decide on the class's operation/methods.

2. The Contents of a Class 3 main parts of a class public class ClassName { Fields // variables used by all methods Constructor(s) // method(s) that initialize an object Methods (functions) } 3 main parts of a class

Fields Fields are the variables (data) used by an object. Also known as instance variables. public class Stack { private int store[]; private int max_len; private int top;   // all methods can use fields } type visibility variable name private int top;

Constructors A constructor is a special method which initializes an object's fields. A constructor has the same name as the class. public Stack(int size) { store = new int[size]; max_len = size-1; top = -1; }

Methods Methods are functions very like C/C++ functions/methods. The methods that are visible to the user (public) in a class depend on the interface of the thing being implemented e.g. the stack interface → public methods that a user can call

3. A Stack Class continued // Stack.java // Written by the Stack implementor public class Stack { private int store[]; // hidden data private int max_len; private int top; public Stack(int size) // visible method { store = new int[size]; max_len = size-1; top = -1; } : continued

public boolean push(int number) { if (top == max_len) return false; top++; store[top] = number; return true; } : continued

public boolean pop() { if (top == -1) return false; top--; return true; } public int topOf() { return store[top]; } public boolean isEmpty() { return (top == -1); } } // end of Stack.java

Stack Class Diagram class name fields methods constructor '-' means private '+' mean public

4. Creating a Stack Object // TestStack.java // Written by the Stack user import java.io.*; public class TestStack { public static void main(String args[]) { Stack stk1 = new Stack(10); stk1.push(42); stk1.push(17); stk1.pop(); System.out.println(“Top value is “ + stk1.topOf() ); } } hello object!!

Compilation and Execution $ javac Stack.java $ javac TestStack.java $ java TestStack Top value is 42 Stack.class is in the same directory as TestStack.class.

Notes The user cannot directly access the object's data (fields) because it is private. The user can call methods because they are public the methods are the object's user interface continued

Object creation: has three parts: Stack stk1 = new Stack(10) has three parts: Stack stk1 // create a variable name, stk1 = new // create a Stack object Stack(10) // call the constructor to initialize the object state

Stack Object Diagram Just after object creation: private means the user of the object cannot directly access the fields. stk1 1 2 9 store[] . . . . max_len 9 top -1 The stack object has a copy of the class' fields (data), but uses the methods in the 'class library'.

Meaning of a method call: stk1.push(17) means call the push() method stored in the Stack class, but apply it to the stk1 object Methods work on an object's fields even though the methods are stored in the class.

Stack Object Diagram (later) Just before the call to pop(): stk1 store[] 42 17 . . . . max_len 9 top 1

5. Understanding a Stack Object What does the user need to understand in order to use a Stack object? He only needs to understand the interface e.g. pop push is Empty topOf 17 42 continued

The user does not need to know how things are implemented the user is happy since the interface is simple the implementor is happy since he can change the implementation (e.g. make it faster), and the user will not complain (so long as the interface does not change)

6. A Bad Stack Interface // BadStack.java // Written by the ฺBadStack implementor public class BadStack { private int store[]; private int max_len; public int top; // constructor and methods same as in Stack :

Creating a BadStack Object // TestBadStack.java // Written by the BadStack user import java.io.*; public class TestBadStack { public static void main(String args[]) { BadStack stk1 = new BadStack(10); stk1.push(42); stk1.push(17); stk1.top = 0; stk1.pop(); System.out.println(“Top value is “ + stk1.topOf() ); } } hello object!! ?

Understanding the BadStack Object What does the user need to understand in order to use the BadStack object? He needs to understand the interface and implementation e.g. pop push + store[], top, max_len 17 42

7. Good vs Bad Interfaces A good interface hides the class's implementation all fields are private A good interface can be visualized by the user (e.g the stack diagram) A good interface has easy-to-understand public methods.

Kinds of Methods in an Interface Aside from the constructor, most public methods can be grouped into two types: accessor (get) methods they return information to the user e.g. in Stack: isEmpty(), topOf() mutator (set) methods they change the object's state (its fields) e.g. in Stack: push(), pop()

An Accessor (Get) Method return type visibility modifier method name parameter list (usually empty) public int topOf() { return store[top]; } return statement start and end of method body (block)

A Mutator (Set) Method visibility modifier return type method name parameter(s) public boolean push(int number) { if (top == max_len) return false; top++; store[top] = number; return true; } fields being mutated

8. Creating Two Stack Objects Many objects can be created from a class: : // in main() of TestStack Stack stk1 = new Stack(10); Stack stk2 = new Stack(20); stk1.push(27); stk1.push(13); stk2.push(10); el = stk2.topOf(); : create two objects

Stack Objects Diagrams stk1 store[] 27 13 . . . . max_len 8 top 1 Just before the call to topOf(): stk2 store[] . . . . 10 max_len 19 top

Notes The two objects have two copies of the class's data changes in one object do not affect the other object Both objects use the methods in the class stk1.push(13) means call push() and apply it to the data inside stk1

9. Object Types vs. Primitive Types Foo object a Foo a = new Foo(); object type primitive type int i; i = 32; 32 i Primitive types include: int, float, double, char, byte

Assignment Differences Foo a = new Foo(); Foo b; b = a; copy the link (the reference) a b Foo object int a = 32; int b; b = a; copy the value 32 32 a b

10. A Ticket Machine show balance (the amount of money entered) show price (and other info) print ticket insert money give change The required interface helps the implementor decide on the class’s methods.

10.1. Class Diagram accessor methods accessor/ mutator mutator method (tricky to understand) constructor

10.2 Ticket Machine Class continued public class TicketMachine { private int price; // price of a ticket private int balance; // amount entered by customer private int total; // total money in machine public TicketMachine(int ticketCost) { price = ticketCost; // set the ticket price balance = 0; total = 0; } continued

continued public int getPrice() { return price; } public int getBalance() { return balance; } public int getTotal() { return total; } continued

continued public void insertMoney(int amount) // process money inserted into the machine { if (amount > 0) balance = balance + amount; else System.out.println("Use a positive amount: " + amount); } continued

continued public void printTicket() { if (balance >= price) {// if enough money inserted // Simulate the printing of a ticket. System.out.println("##################"); System.out.println("# Ticket"); System.out.println("# " + price + " baht."); System.out.println(); // Update the total collected with the price. total = total + price; // Reduce the balance by the prince. balance = balance - price; } else // report error System.out.println( "You must insert at least: " + (price - balance) + " more baht."); } // end of printTicket() continued

public int refundBalance() { int amountToRefund; amountToRefund = balance; balance = 0; //clear ticket machine's balance return amountToRefund; //return balance amount } } // end of TicketMachine class

10.3. Local Variables Fields are one sort of variable they store values through the life of an object they are accessible by all the methods Methods can include shorter-lived variables: they exist only as long as the method is being executed they are only accessible from within the method

Local Variable Example A local variable public int refundBalance() { int amountToRefund; amountToRefund = balance; balance = 0; return amountToRefund; } No visibility modifier

10.4. Using a TicketMachine Object public class TMDemo { public static void main(String[] args) TicketMachine tm = new TicketMachine(10); // tickets cost 10 System.out.println("Ticket price: " + tm.getPrice()); System.out.println("Current total: " + tm.getTotal()); System.out.println("Insert 5 baht"); tm.insertMoney(5); :

System.out.println("Insert 10 baht"); tm.insertMoney(10); System.out.println("Current balance: " + tm.getBalance()); tm.printTicket(); System.out.println("Current total: " + tm.getTotal()); :

System.out.println("Request Change"); System.out.println("Change is: " + tm.refundBalance()); System.out.println("Current balance: " + tm.getBalance()); } // end of main() } // end of TMDemo class

Compilation $ javac TicketMachine.java $ javac TMDemo.java TicketMachine.class is in the same directory as TMDemo.class.

Output of java TMDemo Ticket price: 10 Current total: 0 Insert 5 baht Current balance: 15 ################## # Ticket # 10 baht. Current balance: 5 Current total: 10 Request Change Change is: 5 Current balance: 0

TicketMachine Object Diagram Just after object creation: tm price 10 balance total The TicketMachine object has a copy of the class' data, but uses the methods in the 'class library'.