SOFTWARE AND PROGRAMMING 1 Lecture 4: 2.2.11 Ticketing machine details: Constructor, method, static/instance variables Instructor: Prof. Boris Mirkin

Slides:



Advertisements
Similar presentations
Programming for Beginners Martin Nelson Elizabeth FitzGerald Lecture 3: Flow Control I: For Loops.
Advertisements

SOFTWARE AND PROGRAMMING 1 Lecture 3: Ticketing machine: Constructor, method, menu Instructor: Prof. Boris Mirkin web-site
Looking inside classes Fields, Constructors & Methods Week 3.
1 Lecture 23/2/11 Working with an array Array of user-defined objects (if time permits) 2 MARCH, next Wednesday: Reading week - No lecture , but.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 7: User-Defined Functions II.
Chapter 7: User-Defined Functions II
CSCI 1100/1202 April 3, Testing A program should be executed multiple times with various input in an attempt to find errors Debugging is the process.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Immutable Objects and Classes.
Understanding class definitions Looking inside classes 3.0.
Understanding class definitions – Part II –. Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Main.
Scanner class for input Instantiate a new scanner object Scanner in = new Scanner(System.in); Getting input using scanner – int i = scanner.nextInt() –
Understanding class definitions Looking inside classes.
Saravanan.G.
Week 4-5 Java Programming. Loops What is a loop? Loop is code that repeats itself a certain number of times There are two types of loops: For loop Used.
Writing Classes (Chapter 4)
© 2008, Renesas Technology America, Inc., All Rights Reserved 1 Purpose  This training course describes how to configure the the C/C++ compiler options.
1 CSC 201: Computer Programming I B. S. Afolabi. Introduction  3 unit course  2 hours of lecture/week Thursdays 4.00pm – 6.00pm Mondays 4.00pm – 6.00pm.
Java Classes Using Java Classes Introduction to UML.
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.
1. 2 Reference... Student stu; Reference of Student stu When the reference is created it points to a null value. Before access the reference, objects.
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.
SOFTWARE AND PROGRAMMING 1 Lecture TODAY: Python and Java Instructor: Prof. Boris Mirkin web-site
Case study Students. Array of objects Arrays can hold objects (ref to objects!) Each cell in an array of objects is null by default Sample: from student.
JAVA Classes Review. Definitions Class – a description of the attributes and behavior of a set of computational objects Constructor – a method that is.
Lecture 101 CS110 Lecture 10 Thursday, February Announcements –hw4 due tonight –Exam next Tuesday (sample posted) Agenda –questions –what’s on.
Static class members.
Understanding class definitions
Java Arrays and Methods MIS 3023 Business Programming Concepts II The University of Tulsa Professor: Akhilesh Bajaj All slides in this presentation ©Akhilesh.
Java - Classes JPatterson. What is a class? public class _Alpha { public static void main(String [] args) { } You have been using classes all year – you.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
Classes. Student class We are tasked with creating a class for objects that store data about students. We first want to consider what is needed for the.
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.
SOFTWARE AND PROGRAMMING 1 In-class open-book TEST1 on 6/02 Lab SH131: (from ) Ms Mihaela Cocea Room London Knowledge Lab Emerald.
Programming Languages and Paradigms Activation Records in Java.
Bank Account Example public class BankAccount { private double balance; public static int totalAccounts = 0; public BankAccount() { balance = 0; totalAccounts++;
1 Lecture 16/2/11: Contents Local variable Array: the concept Working with an array An advert: Reading week 2 March. No lecture. All are welcome to room.
 CSC111 Quick Revision. Problem Write a java code that read a string, then show a list of options to the user to select from them, where:  L to print.
Classes - Intermediate
College Board Topics – A.P. Computer Science A Program Design - Read and understand a problem's description, purpose, and goals; Apply data abstraction.
1 Lecture # 2. * Introducing Programming with an Example * Identifiers, Variables, and Constants * Primitive Data Types * Byte, short, int, long, float,
Introduction to programming in java Lecture 22 Arrays – Part 2 and Assignment No. 3.
Understanding class definitions Exploring source code 6.0.
Comp1004: Building Better Objects II Encapsulation and Constructors.
Methods. Creating your own methods Java allows you to create custom methods inside its main body. public class Test { // insert your own methods right.
Programming in Java Transitioning from Alice. Becomes not myFirstMethod but …. public static void main (String[] arg) { // code for testing classes goes.
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.
Java 5 Class Anatomy. User Defined Classes To this point we’ve been using classes that have been defined in the Java standard class library. Creating.
SOFTWARE AND PROGRAMMING 1
Examples of Classes & Objects
Yanal Alahmad Java Workshop Yanal Alahmad
Chapter 4: Writing Classes
Something about Java Introduction to Problem Solving and Programming 1.
User-Defined Classes and ADTs
Understanding class definitions
Computing Adjusted Quiz Total Score
Classes & Objects: Examples
Assignment 7 User Defined Classes Part 2
User-Defined Classes and ADTs
CS2011 Introduction to Programming I Methods (II)
Understanding class definitions
Chapter 7: User-Defined Functions II
F II 3. Classes and Objects Objectives
Names of variables, functions, classes
CS 1054: Lecture 2, Chapter 1 Objects and Classes.
Previous Lecture: Today’s Lecture: Reading (JV):
Presentation transcript:

SOFTWARE AND PROGRAMMING 1 Lecture 4: Ticketing machine details: Constructor, method, static/instance variables Instructor: Prof. Boris Mirkin Course Assistant: Lab/WebCT/Tests/Assignments: Mr Martin O’Shea Test next week: open-book IN-CLASS: only those registered at B12 Cruciform will be marked (Pls, NOTE THIS)

2 Test1 9/2/11 awareness Test1 subjects: Variable: type, declaration, initialisation Expression Loop for Loop while if( )… else if( )... else Simple class structure Strings Simple methods

3 Ticket Machine Imitates issuing flat-rate tickets Three variables needed: price – for ticket price balance – for the user’s money total – for money received from customers Three assessor methods for getting each of the variables Three mutator methods for - entering customer’s money - issuing a ticket - getting refunded

4 Organising a menu //--- ‘menu’ method for choosing action public static int menu() { TextIO.putln(); TextIO.putln("Please enter a number: "); TextIO.putln(" 0 - to quit "); TextIO.putln(" 1 - to get a ticket price "); TextIO.putln(" 2 - to put money and get a ticket "); TextIO.putln(" 3 - to get refunded "); TextIO.putln(" 4 - to get statistics "); int action=TextIO.getInt(); return action; }

5 Main method using menu: right? public static void main(String[ ] args){ int MeItem=1; while (MeItem!=0){ MeItem=menu();// a method if (MeItem==1){ int pp=getPrice(); // a method System.out.println("The ticket price is "+pp+" pence ");} else if (MeItem==2) { System.out.println("Please key in the money inserted, in pence"); int money.insert=TextIO.getInt(); insertMoney(money_insert); printTicket();} else if (MeItem==3) { int refund=refundBalance(); System.out.println("Please take your refund " + refund);} else {int tt=getTotal(); int bb=getBalance(); System.out.println("The total for tickets: "+tt);} }//end of while for choosing action } //end of main

6 Main method using menu: WRONG! WHY? There are some deficiencies in the program: no difference between option 4 and !(1 | 2 | 3) – but this wouldn’t make the class fail Because main method is static, but other methods and variables are not: A Java Commandment : You shalt not utilise non static items in a static method! What to do? Either –Make other methods and variables static too; this works but may be at odds with flexibility considerations –Introduce an instance of the class into main method – make the constructor working – and use all methods and variables from the instance – let us do this!

7 Main method using menu: Right (I) public static void main(String[ ] args){ System.out.println("Please enter a ticket price "); int pi=TextIO.getInt(); TM atm=new TM(pi); int MeItem=1; while (MeItem!=0){ MeItem=menu();// a method if (MeItem==1){ int pp=atm.getPrice(); // a method System.out.println("Ticket price is "+pp);} // continued next page

8 Main method using menu: Right (II) else if (MeItem==2) { System.out.println(“Key in the money inserted in pence"); int money_insert=TextIO.getInt(); atm.insertMoney(money_insert); atm.printTicket();} else if (MeItem==3) { int refund=atm.refundBalance(); System.out.println("Please take your refund " + refund);} else {int tt=atm.getTotal(); int bb=atm.getBalance(); System.out.println("The total for tickets: "+tt);} }//end of loop while for choosing action } //end of main

9 Constructor Constructor is a special method that –Has the same name as the class –No return type (nor “return”) –Is called with modifier “new” to reserve a memory space for an object of class type (an instance) List of parameters, as well as the block, can be user defined The constructor with no parameters is available by default (like Const(){ }; )

10 Static and instance variables Static variable:belongs to its class, and it is shared by all class instances, with the same value Instance variable:a class variable without the “static” modifier, is shared by all class instances, but its values can differ in different instances Local variable: is created within a method or instance in a { } block. Its scope is limited within the block.

11 Example (1) public class TesNum { int instVar = 1; static int statVar = 10; TesNum() { System.out.println("test: " + instVar + " and " + statVar); instVar = 7; statVar = 5; } \\ constructor

12 Example(2) public static void main(String[] args) { TesNum alpha1 = new TesNum(); alpha1.instVar = 3; alpha1.statVar = 6; //syn. to: TesNum.statVar = 6; TesNum alpha2 = new TesNum(); System.out.println("inst: " + alpha1.instVar + " and " + alpha2.instVar); System.out.println("stat: " + alpha1.statVar + " and " + alpha2.statVar); //System.out.print("mix: " + instVar + " and " + statVar); wrong } //end of main } //end of class

13 What’s going on in TesNum instVar statVar 1. With the class: 1 (in class) At the constructo r in class (virtual): After alpha1 :Constructor prints:1 and 10 3 (within alpha1)6 4. After alpha2 :Constructorprints:1 and6 7 (within alpha2)5 5. Method main prints:3 and 7 5 and 5

14 A method added: public int SS(int a){ int b=instVar; int sum=0; if (a>b){ //swap a and b int c=b; b=a; a=c;} for(int i=a;i<=b;i++) sum=sum+i; return sum; } // computes the sum of integers from a to b int b1=alpha1.SS(statVar); int b2=alpha2.SS(statVar); System.out.println("sum : " + b1 + " and " + b2);

15 Sums to be printed From alpha1: a=5, b=3 The sum: 3+4+5=12, that is, b1=12 From alpha2: a=5, b=7 The sum: 5+6+7=18, that is, b2=18 The print: sum: 12 and 18

16 References to object variables and methods Examples from TesNum alpha1.statVar alpha2.instVar TesNum.statVar from TesNMod alpha1.SS(statVar)