Java Classes and Objects

Similar documents
Exceptions and Design

Stack. 4. In Stack all Operations such as Insertion and Deletion are permitted at only one end. Size of the Stack 6. Maximum Value of Stack Top 5

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and More

Stacks. Chapter 5. Copyright 2012 by Pearson Education, Inc. All rights reserved

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

Class API. Class API. Constructors. CS200: Computer Science I. Module 19 More Objects

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

C++ (Non for C Programmer) (BT307) 40 Hours

Index COPYRIGHTED MATERIAL

Introduction to Programming Using Java (98-388)

Object Oriented Programming

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

9 Working with the Java Class Library

COMP 202 Recursion. CONTENTS: Recursion. COMP Recursion 1

Java Primer 1: Types, Classes and Operators

CprE 288 Introduction to Embedded Systems Exam 1 Review. 1

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

Programming II (CS300)

Introduction to Programming (Java) 4/12

CS201- Introduction to Programming Current Quizzes

Object Oriented Programming

Programming in C and C++

Short Notes of CS201

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach.

Searching and Strings. IST 256 Application Programming for Information Systems

CS201 - Introduction to Programming Glossary By

Largest Online Community of VU Students

Common Misunderstandings from Exam 1 Material

Data Structures & Algorithm Analysis. Lecturer: Souad Alonazi

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

CS 211 Programming Practicum Spring 2018

Stack ADT. ! push(x) puts the element x on top of the stack! pop removes the topmost element from the stack.

Associate Professor Dr. Raed Ibraheem Hamed

3. Java - Language Constructs I

CSE143 Exam with answers Problem numbering may differ from the test as given. Midterm #2 February 16, 2001

Abstract Data Types. Stack. January 26, 2018 Cinda Heeren / Geoffrey Tien 1

CSC Java Programming, Fall Java Data Types and Control Constructs

1. Stack Implementation Using 1D Array

1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE?

CS350: Data Structures Stacks

CS 211 Programming Practicum Spring 2017

Data Structure. Recitation IV

CS 211 Programming Practicum Fall 2018

CSC 1600 Memory Layout for Unix Processes"

Objectives. Introduce static keyword examine syntax describe common uses

Working with Strings. Lecture 2. Hartmut Kaiser. hkaiser/spring_2015/csc1254.html

CS201 Some Important Definitions

CMSC 341 Lecture 6 Templates, Stacks & Queues. Based on slides by Shawn Lupoli & Katherine Gibson at UMBC

Computer Science CS221 Test 2 Name. 1. Give a definition of the following terms, and include a brief example. a) Big Oh

Object Oriented Modeling

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

Fundamental Concepts and Definitions

In Java there are three types of data values:

7.1 Optional Parameters

Object Oriented Software Design II

double d0, d1, d2, d3; double * dp = new double[4]; double da[4];

1 P a g e A r y a n C o l l e g e \ B S c _ I T \ C \

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

COMP-202. Recursion. COMP Recursion, 2011 Jörg Kienzle and others

Java Programming Tutorial 1

Full file at

Decaf Language Reference Manual

Outline. Introduction Stack Operations Stack Implementation Implementation of Push and Pop operations Applications. ADT for stacks

Intro to OOP Visibility/protection levels and constructors Friend, convert constructor, destructor Operator overloading a<=b a.

Creating an object Instance variables

Abstract Data Types and Data Structures

Instantiation of Template class

DS Assignment II. Full Sized Image

182 review 1. Course Goals

Chapter 12 - Templates

PROFESSOR: DR.JALILI BY: MAHDI ESHAGHI

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

JavaScript. History. Adding JavaScript to a page. CS144: Web Applications

Practice exam for CMSC131-04, Fall 2017

Java Object Oriented Design. CSC207 Fall 2014

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:

String. Other languages that implement strings as character arrays

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

1d: tests knowing about bitwise fields and union/struct differences.

Arrays. Returning arrays Pointers Dynamic arrays Smart pointers Vectors

7 TEMPLATES AND STL. 7.1 Function Templates

Increment and the While. Class 15

BASIC ELEMENTS OF A COMPUTER PROGRAM

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8

Internet & World Wide Web How to Program, 5/e by Pearson Education, Inc. All Rights Reserved.

G52CPP C++ Programming Lecture 13

Where does the insert method place the new entry in the array? Assume array indexing starts from 0(zero).

C++_ MARKS 40 MIN

CMPS 390 Data Structures

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:

MULTIMEDIA COLLEGE JALAN GURNEY KIRI KUALA LUMPUR

OBJECT ORIENTED PROGRAMMING

An Introduction To Writing Your Own Classes CSC 123 Fall 2018 Howard Rosenthal

CSE 142 Su 04 Computer Programming 1 - Java. Objects

Main loop structure. A Technical Support System. The exit condition. Main loop body

Name: Username: I. 20. Section: II. p p p III. p p p p Total 100. CMSC 202 Section 06 Fall 2015

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING B.E SECOND SEMESTER CS 6202 PROGRAMMING AND DATA STRUCTURES I TWO MARKS UNIT I- 2 MARKS

12/22/11. Java How to Program, 9/e. public must be stored in a file that has the same name as the class and ends with the.java file-name extension.

Selected Questions from by Nageshwara Rao

Transcription:

Table of contents 1 Introduction Case Study - Stack 2 3 Integer String

Case Study - Stack Introduction

Case Study - Stack Classes Template for creating objects Definition of State (What it knows) Definition of Behaviour (What it can do)

Case Study - Stack Object (Instance) A single realization of a Class Has a State Behaviours can be invoked on it

Case Study - Stack Analogies from real life People - John and Mary are Instances of a Human Class Human is an abstract definition just like a Class John and Mary are concrete, they exist Houses - Two houses from the same blueprint can be created The blueprints can define a door and how it should open The door can actually be opened on a specific house

Case Study - Stack Case Study - Stack

Case Study - Stack Case Study - Stack What is the behaviour we want?

Case Study - Stack Case Study - Stack What is the behaviour we want? We want to be able to create a stack object

Case Study - Stack Case Study - Stack What is the behaviour we want? We want to be able to create a stack object We want to request the stack to push an element

Case Study - Stack Case Study - Stack What is the behaviour we want? We want to be able to create a stack object We want to request the stack to push an element We want to query the stack about its top element

Case Study - Stack Case Study - Stack What is the behaviour we want? We want to be able to create a stack object We want to request the stack to push an element We want to query the stack about its top element We want to request the stack to pop an element

Case Study - Stack Case Study - Stack What is the behaviour we want? We want to be able to create a stack object We want to request the stack to push an element We want to query the stack about its top element We want to request the stack to pop an element We want to query the stack about its size

Case Study - Stack Case Study - Stack What is the behaviour we want? We want to be able to create a stack object We want to request the stack to push an element We want to query the stack about its top element We want to request the stack to pop an element We want to query the stack about its size Implementation constraints We will build a stack that can hold up to X elements We will build a stack of integers

What should happen when we try to use top/pop on an empty stack?

What should happen when we try to use top/pop on an empty stack? What should happen when we try pushing into a full stack?

Note What should happen when we try to use top/pop on an empty stack? What should happen when we try pushing into a full stack? We will solve the issues using the tools we know, for now. We will see better ways of dealing with these problems at later stages of the course

Data structure What basic data types do we need to represent a stack? Array of elements Integer value to indicate the position of the top in the array Do we need an integer value for the size of the array?

Class structure overview 6 class BoundedPositiveIntegerStack { 9 static final int EMPTY_STACK = -1; 14 private int [] elements ; 17 private int numberofelements ; 34 BoundedPositiveIntegerStack () { 44 boolean push ( int element ) { 64 int pop () { 80 int top () { 96 int size () { 109 }

Class structure overview - Class definition 6 class BoundedPositiveIntegerStack { 9 static final int EMPTY_STACK = -1; 14 private int [] elements ; 17 private int numberofelements ; 34 BoundedPositiveIntegerStack () { 44 boolean push ( int element ) { 64 int pop () { 80 int top () { 96 int size () { 109 }

Class definition 3 /** 4 * A bounded stack of positive integers. 5 */ 6 class BoundedPositiveIntegerStack {... Note This code will be located in a file called BoundedPositiveIntegerStack.java, the name of the file must match the name of the class.

Class structure overview - Variables 6 class BoundedPositiveIntegerStack { 9 static final int EMPTY_STACK = -1; 14 private int [] elements ; 17 private int numberofelements ; 34 BoundedPositiveIntegerStack () { 44 boolean push ( int element ) { 64 int pop () { 80 int top () { 96 int size () { 109 }

Field / Member variables Just like the definition of a regular variable Only inside the class block instead of a specific method This defines the Possible States of our class 13 // array of elements 14 private int [] elements ; 15 16 // number of elements in our stack 17 private int numberofelements ;

Field variables VS Static variables Member variable Memory allocated per Object Static variable Memory allocated per Class A global variable in a context of a specific class 8 // indication that the stack is empty 9 static final int EMPTY_STACK = -1; Note Static variables should be avoided, mostly used for defining const values in a context of a class

Class structure overview - Constructors 6 class BoundedPositiveIntegerStack { 9 static final int EMPTY_STACK = -1; 14 private int [] elements ; 17 private int numberofelements ; 34 BoundedPositiveIntegerStack () { 44 boolean push ( int element ) { 64 int pop () { 80 int top () { 96 int size () { 109 }

Constructors A special function that will be called, when object is created Has to be the same name as the class We can define what parameters are needed to create an object Initializes State of Objects 19 /** 20 * constructor with configurable max stack size. 21 * 22 * @param maxsize maximum number of elements in stack. 23 */ 24 BoundedPositiveIntegerStack ( int maxsize ) { 25 // create a new array 26 this. elements = new int [ maxsize ]; 27 // initialize number of elements to 0 ( empty stack ) 28 this. numberofelements = 0; 29 } Note Notice that there is no return value in a constructor definition

The keyword this A reference to self, for accessing your own field variables / methods 19 /** 20 * constructor with configurable max stack size. 21 * 22 * @param maxsize maximum number of elements in stack. 23 */ 24 BoundedPositiveIntegerStack ( int maxsize ) { 25 // create a new array 26 this. elements = new int [ maxsize ]; 27 // initialize number of elements to 0 ( empty stack ) 28 this. numberofelements = 0; 29 } Note Using this is not required but it s a good practice to distinguish between local variables and field variables

the new statement Creates a new object of the requested class (allocates memory on the Heap) Calls the constructor 14 BoundedPositiveIntegerStack stacka = 15 new BoundedPositiveIntegerStack (1000) ;

Memory regions Stack (not to be confused with the Stack we implemented) Holds information about what function your are in now and what functions called it Holds all the basic local variables for each executed function Heap Holds all non basic variables Typically much bigger than the Stack

Constructors - continued We can define multiple constructors as long as they have different parameters (Constructor overloading) A constructor without any parameters is called a Default Constructor 10 // the default max size of the stack 11 static final int DEFAULT_NEW_STACK_SIZE = 50;... 34 /** 35 * Default constructor 36 */ 37 BoundedPositiveIntegerStack () { 38 // create a new array ( default size ) 39 this. elements = new int [ DEFAULT_NEW_STACK_SIZE ]; 40 // initialize number of elements to 0 ( empty stack ) 41 this. numberofelements = 0; 42 }

Constructors - continued 2 Why replicate almost the same code twice? We can call other constructors using this() 10 // the default max size of the stack 11 static final int DEFAULT_NEW_STACK_SIZE = 50;... 24 BoundedPositiveIntegerStack ( int maxsize ) { 25 // create a new array 26 this. elements = new int [ maxsize ]; 27 // initialize number of elements to 0 ( empty stack ) 28 this. numberofelements = 0; 29 }... 31 /** 32 * constructor with default max stack size. 33 */ 34 BoundedPositiveIntegerStack () { 35 this ( DEFAULT_NEW_STACK_SIZE ); 36 }

Using overloaded constructors Calls the correct Constructor based on the passed parameters 13 // create a two instances of the stack class 14 BoundedPositiveIntegerStack stacka = 15 new BoundedPositiveIntegerStack (1000) ; 16 17 BoundedPositiveIntegerStack stackb = 18 new BoundedPositiveIntegerStack (); Note If two constructors had the same parameters, you wouldn t be able to know which one to call either!

Class structure overview - Methods 6 class BoundedPositiveIntegerStack { 9 static final int EMPTY_STACK = -1; 14 private int [] elements ; 17 private int numberofelements ; 34 BoundedPositiveIntegerStack () { 44 boolean push ( int element ) { 64 int pop () { 80 int top () { 96 int size () { 109 }

Methods Functions belonging to our class Can be invoked on an Instance of a class Define the Behaviour of the class

Methods - size Query the size of the stack: 91 /** 92 * The number of elements currently in the stack. 93 * 94 * @return number of elements. 95 */ 96 int size () { 97 return this. numberofelements ; 98 }

Methods - push Request the stack to push an element: 38 /** 39 * push an element into the stack. 40 * 41 * @param element the element to push into the stack. 42 * @return true if element was added to the stack, false otherwise. 43 */ 44 boolean push ( int element ) { 45 // check if we have space to add a new element, 46 // and the element is indeed positive 47 if ( element >= 0 && numberofelements < this. elements. length ) { 48 // add the new element 49 this. elements [this. numberofelements ] = element ; 50 this. numberofelements += 1; 51 // return success of adding the element 52 return true ; 53 } else { 54 // return failure since we have no more space left 55 return false ; 56 } 57 }

Methods - top Query the stack about its top element: 8 // indication that the stack is empty 9 static final int EMPTY_STACK = -1;... 75 /** 76 * The top element in the stack. 77 * 78 * @return top element, or EMPTY_STACK if nothing is the stack. 79 */ 80 int top () { 81 // check if we have any elements in the stack 82 if (this. numberofelements == 0) { 83 // return an indication that the stack is empty 84 return EMPTY_STACK ; 85 } else { 86 // return the correct element 87 return this. elements [this. numberofelements - 1]; 88 } 89 }

Methods - pop Request the stack to pop an element: 59 /** 60 * Pop element from the stack. 61 * 62 * @return top element, or EMPTY_STACK if nothing is the stack. 63 */ 64 int pop () { 65 // get the element on top of the stack 66 int top = top (); 67 // decrement the number of elements, unless the stack is already empty 68 if ( top!= EMPTY_STACK ) { 69 this. numberofelements -= 1; 70 } 71 // return the element 72 return top ; 73 }

How to arrange all the pieces? Standard order of all components: 1 Statics 2 Field variables 3 Constructors 4 Methods

Using methods calling methods on objects using the. (dot) operator 20 // push 1 to 10 into the stack 21 for ( int i = 1; i <= 10; i += 1) { 22 stacka. push (i); 23 } 24 25 // push all even numbers between 1 and 10 26 for ( int i = 1; i <= 5; i += 1) { 27 stackb. push (i * 2); 28 }

Accessing static variables Using the. (dot) operator on the name of the class (as it s a per class variable) 33 // push elements in A into B 10 to 1 34 while ( stacka.top ()!= BoundedPositiveIntegerStack. EMPTY_STACK ) { 35 stackb.push ( stacka.pop ()); 36 } Note Can be accessed through a variable but you should never use it, it s confusing!

Additional Examples Show Towers Of Hanoi code Show compilation of multiple files in command line

Integer String

Integer String Integer A Simple object wrapper of a single int value 1 Integer number = new Integer (7) Useful static information 1 Integer. MAX_VALUE 2 Integer. MIN_VALUE Can be null 1 Integer number = null ; Note How can we improve our previous?

Integer String Integer - continued int will convert to Integer automatically 1 Integer number = 7; Natural assignment 1 int a = 8; 2 Integer b = a; Unnatural assignment, can you see the problem? 1 Integer a = null ; 2 int b = a;

Integer String String Every String is an object 1 String str1 = " Hello World "; 2 String str2 = " Goodbye World "; 3 String str3 = " Goodbye World "; Check how long it is 1 str1. length () // 11 Compare two Strings (why == wont work?) 1 str1. equals (str2 ) // returns false 2 str2. equals (str3 ) // returns true

Integer String String - continued Get a specific character inside a String 1 String str = " Boring "; 2 char c = str. charat (2) ; // returns r Check prefix / postix 1 String str = " 12345 "; 2 str. startswith ("12"); // returns true 3 str. endswith ("45"); // returns true Change case: 1 String str = " abc "; 2 str. touppercase (); // returns new String "ABC "

Integer String String - continued 2 Remove prefix and postfix whitespaces 1 String str = " Hello "; 2 str.trim (); // returns new String " Hello " Search for a sub string 1 String str = " 12345 "; 2 str. indexof ("34"); // returns 2 3 str. indexof ("78"); // returns -1 to indicate sub string not found Much more in the JavaDoc http://docs.oracle.com/javase/6/docs/api/java/lang/ String.html

Integer String Summary 1 Introduction Case Study - Stack 2 3 Integer String