Scheme -> Java Conversion Course 2001 Lab Session 2/2.

Slides:



Advertisements
Similar presentations
Classes and Objects. What is Design? The parts of the software including – what information each part holds – what things each part can do – how the various.
Advertisements

CS0007: Introduction to Computer Programming Introduction to Classes and Objects.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Lecture 2: Object Oriented Programming I
Access to Names Namespaces, Scopes, Access privileges.
1 Chapter 7 User-Defined Methods Java Programming from Thomson Course Tech, adopted by kcluk.
19-Jun-15 Access to Names Namespaces, Scopes, Access privileges.
Writing methods and Java Statements. Java program import package; // comments and /* … */ and /** javadoc here */ public class Name { // instance variables.
CS 106 Introduction to Computer Science I 11 / 15 / 2006 Instructor: Michael Eckmann.
Classes, methods, and conditional statements We’re past the basics. These are the roots.
1 Methods Overview l Closer Look at Methods l Parameter passing l Passing parameters by value l Passing parameters by reference.
1 Memory Model of A Program, Methods Overview l Closer Look at Methods l Memory Model of JVM »Method Area »Heap »Stack l Preview: Parameter Passing.
1 Methods Overview l Closer Look at Methods l Parameter passing l Passing parameters by value l Passing parameters by reference.
28-Jun-15 Access to Names Namespaces, Scopes, Access privileges.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 7 User-Defined Methods.
Chapter 7: User-Defined Methods
COMP 14: I/O and Boolean Expressions May 24, 2000 Nick Vallidis.
Introduction to Methods
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.
CS 106 Introduction to Computer Science I 04 / 13 / 2007 Friday the 13 th Instructor: Michael Eckmann.
CMP-MX21: Lecture 6 Objects & Methods 1 Steve Hordley.
Writing Classes (Chapter 4)
Object Oriented Programming Philosophy. Part 1 -- Basic Understanding & Encapsulation.
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.
CSC Programming I Lecture 8 September 9, 2002.
Lecture 2: Classes and Objects, using Scanner and String.
Java Quiz Bowl A fun review of the Java you should know from CMPT 201 If you don’t know the answers - this week is for you to study up!
Chapter 7 Objects and Classes 1 Fall 2012 CS2302: Programming Principles.
CS61B L03 Building Objects (1)Garcia / Yelick Fall 2003 © UCB  Dan Garcia ( Kathy Yelick  (
Agenda Review C++ Library Functions Review User Input Making your own functions Exam #1 Next Week Reading: Chapter 3.
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
First Programs CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Programs and Classes A program is made up from classes Classes may be grouped into packages A class has two parts static parts exist independently Non-static.
Programming in Java CSCI-2220 Object Oriented Programming.
Writing Static Methods Up until now, we have been USING (calling) static methods that other people have written. Now, we will start CREATING our own static.
Odds and Ends. CS 21a 09/18/05 L14: Odds & Ends Slide 2 Copyright © 2005, by the authors of these slides, and Ateneo de Manila University. All rights.
CIS Intro to JAVA Lecture Notes Set July-05 GUI Programming – Home and reload buttons for the webbrowser, Applets.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
Using Objects. 6/28/2004 Copyright 2004, by the authors of these slides, and Ateneo de Manila University. All rights reserved L7: Objects Slide 2 Java.
Java Class Structure. Class Structure package declaration import statements class declaration class (static) variable declarations* instance variable.
CS1101 Group1 Discussion 10 Lek Hsiang Hui comp.nus.edu.sg
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
Exceptions. Exception  Abnormal event occurring during program execution  Examples Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
Inheritance and Subclasses CS 21a. 6/28/2004 Copyright 2004, by the authors of these slides, and Ateneo de Manila University. All rights reserved L16:
Catie Welsh March 23,  Lab 6 due Friday by 1pm 2.
Scheme -> Java Conversion Course 2001 Lab Session 1/2.
CS2102: Lecture on Abstract Classes and Inheritance Kathi Fisler.
Topic 8Classes, Objects and Methods 1 Topic 8 l Class and Method Definitions l Information Hiding and Encapsulation l Objects and Reference Classes, Objects,
1 Project 2: Using Variables and Expressions. 222 Project 2 Overview For this project you will work with three programs Circle Paint Ideal_Weight What.
Java: Variables and Methods By Joshua Li Created for the allAboutJavaClasses wikispace.
BIT 115: Introduction To Programming Professor: Dr. Baba Kofi Weusijana (say Doc-tor Way-oo-see-jah-nah, Doc-tor, or Bah-bah)
OOP Basics Classes & Methods (c) IDMS/SQL News
Structured Programming Dr. Atif Alhejali Lecture 4 Modifiers Parameters passing 1Structured Programming.
CSE 501N Fall ’09 07: Iteration 17 September 2009 Nick Leidenfrost.
Introduction to Exceptions in Java CS201, SW Development Methods.
MT311 Java Application Development and Programming Languages Li Tak Sing( 李德成 )
Chapter 7 User-Defined Methods.
Content Programming Overview The JVM A brief look at Structure
Namespaces, Scopes, Access privileges
Subroutines Idea: useful code can be saved and re-used, with different data values Example: Our function to find the largest element of an array might.
Defining Your Own Classes Part 1
Writing Methods AP Computer Science A.
Namespaces, Scopes, Access privileges
JAVA CLASSES.
Exceptions.
Exceptions.
Previous Lecture: Today’s Lecture: Reading (JV):
Presentation transcript:

Scheme -> Java Conversion Course 2001 Lab Session 2/2

The Scheme->Java Conversion Course 2000/2001 Webpage has been put up. You can find the lecture notes, lab notes and lab answers there. The link has been set up at

Today, we’re going to learn how to write methods and classes, but first… let us go over the answer to Lab 1 Qn 1

Classes We learnt during the lecture that classes are like templates/blueprints. When you look at a.java file, you will notice that except for the import statements, the rest of the code is written in classes. During the lecture, it was also mentioned that classes, being templates, are just lying there, having no action of their own. Since a.java file is made up of “dead” classes, how does it run? How did your HelloWorld.java work?

Classes - The Method “main” In the Java programs you have written so far, you’ve probably noticed this method : public static void main(String[] args) throws Exception Basically, when you run a class (ie. you type java test ), Java will look in that for the method main - it is a reserved keyword in Java In a.java file, there can be many classes, but usually, there will only be one class that will contain the method “main”…during our cs1102 last sem, we have been taught the habit of naming that important class main (so to run it, we type java main )

Classes - The Method “main” Example of what I mean : class main { public static void main(String[] args) throws Exception { //some running code here }

Methods Hmm…since “main” is a method, why does it have extra parameters in front of it (public static), instead of the usual method format : return-type method-name(arguments) { //body } The keyword public is an accessibility modifier, while the keyword static is the static modifier. Huh??

Accessiblity Modifiers Remember what I said about.java files usually having more than 1 class? Well, the accessibility modifiers will determine how accessible the method will be. If I define a method to be public, the method can be called up by other classes. If I define the method to be private, the method can only be used within the class itself Think back on your Scheme. When you define a procedure in the buffer, it can be used by other procedures in the buffer. But, if inside proc A, we define another proc B inside…can it be used by other procedures besides proc A, where it is defined in?

Accessiblity Modifiers Scheme eg : (define (procA a b) (define (procB c d) …..)) (define (myproc k) …) Now…can we call procB from inside myproc? procB can only be seen and used by procA In Java, procA and myproc would be considered public whereas procB is considered private.

Accessiblity Modifiers Java eg : class myType { public int squareA(int x) { … } private double logA(int y) {… } } /* create a variable based on the class myType */ myType calculator = new myType( ); calculator.squareA(…); //valid statement calculator.logA(…); //invalid statement logA( ) can only be used within class myType, where it’s defined. A valid example is that of squareA( ) using logA ( ) to help in some processing of data.

Accessiblity & Static Modifiers Hope’s that clear enough about the accessibility modifiers public and private (actually there’s another modifier protected, but we won’ t cover that - hardly used in cs1102) Now, let’s look at the static modifier… Oh ya, the accessibility and static modifiers can be applied to variables also, eg : private static int x;

Static Modifier Usually, when we want to call a method, we have to create an instance. Eg : when we want to use substring( ), we need to create a String variable, and then call it by reference to the String variable. String s = “Hello!”; s.substring(2); You can’t just call by reference to the class, ie. you call String.substring(2); - it’s not declared static, meaning that substring( ) is only made available through an instance of the String class.

Static Modifier However, there are some static methods in the String class, for example, the method valueOf( ) This method will take in any primitive data type and convert it to a String. So, you can call String.valueOf(true), which will return you the string “true”. Similarly, String.valueOf(23) will return you the string “23”

Static Modifier That’s why the method main( ) is declared static. When Java runs the code, who’s going to create a variable of type main (the class) and call the main method? Basically, when the static modifier is applied to a variable or method, it becomes available all the time, right from the beginning of the program runtime. Regarding methods, if static is not applied, then the method is only available when you create an instance and call by that instance.

Static Variable = = Class Variable When you declare a variable as static, it becomes a class variable, and is shared by all instances of that class. Eg : class example { static int bankbalance; example (int amt)//constructor { bankbalance = amt; } public int withdraw(int amt) { bankbalance = bankbalance - amt; return bankbalance; }

Static Variable = = Class Variable Note that the variable bankbalance is static - it will be shared among all the other instances. For non-static variables, each instance has its own personal copy - not affected by others example first = new example(500); example second = new example(300); System.out.println(first.bankbalance); //not 500, but 300 System.out.println(second.bankbalance); //300 System.out.println(first.withdraw(150)); //150 System.out.println(second.withdraw(150)); //0, not 150 All instances of class example share the same static variable bankbalance.

Sideline : the keyword final When you declare a variable as final, its value cannot be changed throughout the whole program. This in Pascal and C is called a constant. Eg : final int x = 5; x = 6;//this will give error! This comes in useful when you want to set up constants - at the same time implying that you do not want anyone or any part of the code to “accidentally” change the value. An example will be the setting up of the constant pi final double pi = ;

Lab Qn 1 Ok…this lab is to help you practise how to write methods and classes. Remember your bank account problem in Scheme? We are going to do that. Your.java file will have 2 classes, main and BankAcc The class main will contain the method main( ), which will contain the code to run the whole program

Lab Qn 1 The class BankAcc will contain the account number, the name of the account holder, and the balance in his account. Since you are going to create bank accounts, ie. variables based on the BankAcc class, you need to define the constructor for the BankAcc class The constructor is responsible for initialising the new object/instance, in this case, initialise the name, account number and balance to proper values

Lab Qn 1 Besides the constructor (every class has a constructor by default), your BankAcc class must have 2 other methods - a deposit( ) method and a withdraw( ) method. So…your BankAcc class will look something like this : class BankAcc { //your properties/variables here BankAcc (int accno, String name, int balance) { ….. } … … deposit ( … ) { … } … … withdraw ( … ) { … } } //end class

Lab Qn 1 Ok…first, go into pico, type in the following and save as lab2in.txt : 99687,Zion,500 W 50 D ,Cookie,600 W 700 D ,Speed,350 D 200 W 100

Lab Qn 1 Your program will read in that file as input. It must cater for a general number of accounts, ie. you shouldn’t assume that there will always be 3 accounts - the input file can always change to more accounts ,Zion,500 W 50 D ,Cookie,600 W 700 D ,Speed,350 D 200 W 100 Every account is described in 3 lines. 1st line : account-no, name, initial-balance 2nd line : transaction amount 3rd line : transaction amount For transaction, “W” means withdraw, “D” mean deposit Be careful how you tokenize the 1st lines !

Lab Qn 1 In CS1102, you will be often asked to read input provided by a text file. There is NO need to use FileInputStreamReader. Just define your BufferedReader as normal. BufferedReader stdin = new BufferedReader( new InputStreamReader(System.in)); The only difference is that when you run the class, you type : java main < lab2in.txt When you use stdin.readLine( ), it will then read one line from the input provided. The text file replaces the user.

Lab Qn 1 Ok…so your program is supposed to read in these info. Have a loop that will keep reading in this info and processing it until there is no more input. String s; while ( (s=stdin.readLine( )) != null ) //means still have input { //your code }

Lab Qn 1 With every account (3 lines of text), create a new account based on your BankAcc class, and process the transactions. After each transaction, you should print out the account no, name, and balance remaining in that account This is what your output should be : Zion Zion Cookie Cookie Speed Speed 450

Lab Qn 1 I will post the answers on my webpage. When all the materials for this course has been revised and checked thru, I will ask Dr Razvan to you all the webpage address…but here it is now, just for your reference : You may download today’s notes from the webpage now and use it as reference for your programming of this lab That’s all, folks! You may start now :)

Good luck for your CS1102 next sem, Schemers 2001! And thanks to all the Schemers 99 who have willingly forked out their precious holiday time to help out for this course (^ v ^) /* The End */