Top Banner
CS116 OBJECT ORIENTED PROGRAMMING II LECTURE 1 Part II GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology- George Koutsogiannakis 1
39

CS116 OBJECT ORIENTED PROGRAMMING II LECTURE 1 Part II GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology- George Koutsogiannakis.

Dec 22, 2015

Download

Documents

Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: CS116 OBJECT ORIENTED PROGRAMMING II LECTURE 1 Part II GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology- George Koutsogiannakis.

CS116

OBJECT ORIENTED PROGRAMMING IILECTURE 1 Part II

GEORGE KOUTSOGIANNAKIS

Copyright: 2015 Illinois Institute of Technology-George Koutsogiannakis

1

Page 2: CS116 OBJECT ORIENTED PROGRAMMING II LECTURE 1 Part II GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology- George Koutsogiannakis.

REVIEW

• MODIFIERS– Keyword static used in Method signature– Keyword static used in variable declaration– public, private, protected.

• Receiving Input Command Line• Receiving Input via the Scanner– Keyboard.– Reading text file.

• Wrapper Classes.

2

Page 3: CS116 OBJECT ORIENTED PROGRAMMING II LECTURE 1 Part II GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology- George Koutsogiannakis.

Modifiers

• Modifiers are keywords that set visibility and or rights on members of a class.

• Some of the modifier keywords that we should be familiar from CS115 are:

static public private

– Some others that we will use in CS116 are: final abstract protected transient

3

Page 4: CS116 OBJECT ORIENTED PROGRAMMING II LECTURE 1 Part II GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology- George Koutsogiannakis.

The Keyword Static

• The keyword static can be applied to methods and also instance variables of a class.

• Applied to methods:• Methods that have been declared static can be called by using

the name of the class they belong to. Therefore we do not need to instantiate an object of that class in order to invoke its static methods.

• An example is the methods of the library class Math. If we look at the API all the methods of this class have the word static in their signature.

• That means that we can call method pow, as an example, by : double a= Math.pow(a, b);

4

Page 5: CS116 OBJECT ORIENTED PROGRAMMING II LECTURE 1 Part II GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology- George Koutsogiannakis.

Static applied to methods

• We have also seen static used in classes where there is a main method in addition to other methods.

• Rule:– If we want to invoke, from the main method, another

method of the same class (that the main method belongs to) then that method has to be declared static.• There is another way to call a non static method from the main

(assuming that both are in the same class) by creating an object of the same class as the main and invoking the method by using the object.

5

Page 6: CS116 OBJECT ORIENTED PROGRAMMING II LECTURE 1 Part II GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology- George Koutsogiannakis.

Static applied to methods

• The previous rule applies to all methods which are static in a class and not just the main method!

6

Page 7: CS116 OBJECT ORIENTED PROGRAMMING II LECTURE 1 Part II GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology- George Koutsogiannakis.

Static applied to instance variables (attributes) of a class

• If an instance variable (field) is declared static then its value can be seen by all objects of the

same class.• i.e static int id=0; id++; the ++ after the identifier id means that the

its value is incremented by one every time we execute the line of code id++

7

Page 8: CS116 OBJECT ORIENTED PROGRAMMING II LECTURE 1 Part II GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology- George Koutsogiannakis.

Static Variables

• Thus if id=0; id++ causes a new value of id=1 calling id++ again causes a new value of id=2And so on.• If id is also declared static then every time we

increment the value of id every object of the class sees the new value.

8

Page 9: CS116 OBJECT ORIENTED PROGRAMMING II LECTURE 1 Part II GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology- George Koutsogiannakis.

Static Variables

• Suppose that id is a static variable and that it belongs to class Student (template class).

• Suppose that in StudentClient we have instantiated the following objects:Student student1=new Student();

Student student2=new Student();Student student3=new Student();

If the value of id=3 then all the student objects share the same value for id (that is 3).

9

Page 10: CS116 OBJECT ORIENTED PROGRAMMING II LECTURE 1 Part II GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology- George Koutsogiannakis.

Example of static variablepublic class Student {

static int id=0; int currentID=0;

String studentName=" ";public Student() {

id++;currentID=id;studentName=“John Doe”;

}public Student ( String sn){

Studentname=sn;}

followed by accessor /mutator/toString() methods

10

Page 11: CS116 OBJECT ORIENTED PROGRAMMING II LECTURE 1 Part II GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology- George Koutsogiannakis.

Example of static variable

• We notice that in class Student– Every time the constructor is called the value of id

is advanced by one with respect to its previous value.

– Once the value of id is advanced its new value is assigned to a non static variable : currentID.

– That is because the non static variables have values that are dedicated to each object and their values are not shared by all objects of the class.

11

Page 12: CS116 OBJECT ORIENTED PROGRAMMING II LECTURE 1 Part II GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology- George Koutsogiannakis.

Example of static variablepublic class StudentClient{

public static void main(String [] args)

{

Student st1=new Student() // value of id=1 now for st1 . Every time we call the constructor of the class Student id advances by 1

//Also,The value of id is passed to currentID =1 Student st2=new Student() // value of id=2 now for both st1 and st2,

// currentID=1 for st1 but // currentID=2 for st2.

Student st3=new Student() // value of id=3 for st1, st2, st3 // currentID=1 for st1 // currentID=2 for st2// currentID=3 for st3

12

Page 13: CS116 OBJECT ORIENTED PROGRAMMING II LECTURE 1 Part II GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology- George Koutsogiannakis.

Example of static variable

• Therefore we could use the static variable id to track how many objects we have created for that class (i.e. the Student class).

• Notice that the new value of the static variable id is shared amongst all objects of the class.

13

Page 14: CS116 OBJECT ORIENTED PROGRAMMING II LECTURE 1 Part II GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology- George Koutsogiannakis.

Example of static variable• The value of id is the same for each object

student3 is created:

14

Student 1

id-=3

currentID=1

Student 2 Student 3

id-=3 id-=3

currentID=2 currentID=3

Since id is static all 3 objects see its new value when it changes (if a 4th Student was to be created all 4 objects will have id=4).The variable currentID is not static therfore each object sees the value of currentID assigned for that object alone.

Page 15: CS116 OBJECT ORIENTED PROGRAMMING II LECTURE 1 Part II GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology- George Koutsogiannakis.

public and private Modifiers

• Keyword pubic can be applied to java elements:– Data fields (variables), methods, constructors an outer

class, an inner class.– Rule: An element declared public is visible from another

class.

• Keyword private can be applied to Java elements:– Data fields (variables), methods, constructors an inner

class. Can not be applied to an outer class.– Rule: An element declared private is not visible from

another class. Only to members of its own class.

15

Page 16: CS116 OBJECT ORIENTED PROGRAMMING II LECTURE 1 Part II GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology- George Koutsogiannakis.

RECEIVING INPUT

• Different ways to read input into our programs:– User provides input via Command Line when the java

interpreter is called .– Read user provided input via the keyboard using the

Scanner object during execution (interpretation) of the program (you should had learnt this in CS115).

– Read a text file using the Scanner object (you should had learnt this in CS115).

– We will learn later on in this course how to read different types of data files using streams (including writing new data into those files).

16

Page 17: CS116 OBJECT ORIENTED PROGRAMMING II LECTURE 1 Part II GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology- George Koutsogiannakis.

Command Line Input

• Command line implies that:– A DOS window is opened (cmd command from

start menu or assecories->command prompt)– The command line path is pointingt o the path

where the java program file (tehone with the main method) is located.

17

Page 18: CS116 OBJECT ORIENTED PROGRAMMING II LECTURE 1 Part II GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology- George Koutsogiannakis.

Command Line Input• We can obtain input data for a program from the DOS window when we

use the interpret command.• This is called “command line “ input.• i.e

some path………… >java StudentClient arg1 arg2 arg3

Where arg1 arg2 arg3 are the 3 pieces of data (in this example)

that will be read as individual Strings by the main method of the program.

18

Page 19: CS116 OBJECT ORIENTED PROGRAMMING II LECTURE 1 Part II GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology- George Koutsogiannakis.

Command Line Input

• This approach is only good as long as the class has a main method.

• The String array argument of the main method captures the values entered by the user.

• There is no pre determined number of data values that the user can enter from the command line.

19

Page 20: CS116 OBJECT ORIENTED PROGRAMMING II LECTURE 1 Part II GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology- George Koutsogiannakis.

Command Line Input

• Suppose that we have the class StudentClient and that it expects 3 inputs (called arguments) from command line:

• >java StudentClient arg1 arg 2 arg3• public class Student public static void main(String [] args) {

String a=args[0];String b=args[1];String c=args[2];

20

Page 21: CS116 OBJECT ORIENTED PROGRAMMING II LECTURE 1 Part II GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology- George Koutsogiannakis.

Command Line Input

• The Strings a , b , c now have the values that the user entered:

i.e. >java StudentClient Joe , 20, 4.65 thus: a has the value Joe as a String b has the value 20 as a String

c has the value 4.65 as a String

21

Page 22: CS116 OBJECT ORIENTED PROGRAMMING II LECTURE 1 Part II GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology- George Koutsogiannakis.

Command Line Input

• If we wanted to do arithmetic operations with the String versions of values 20 and 4.65 then we have to parse the String verions by using the appropriate wrapper class

• i.e int x= Integer.parseInt(b); results in the int version of the String 20 (int x=20)

double y=Double.parseDouble( c );results in the double version of the String 4.65 (double y=4.65)

22

Page 23: CS116 OBJECT ORIENTED PROGRAMMING II LECTURE 1 Part II GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology- George Koutsogiannakis.

Input Using the Scanner Class

• Sometimes we need to be able to capture input from the user while the program is running..

• One way of providing input to the program is via the keyboard. A DOS window is required.

• Program should be interpreted from command line.• The Scanner library class provides the functionality to

allow us to capture keyboard input (and also read input from a file—we will cover the file reading later)

• Scanner class is part of the Library package java.util – Therefore we have to import the Scanner class

23

Page 24: CS116 OBJECT ORIENTED PROGRAMMING II LECTURE 1 Part II GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology- George Koutsogiannakis.

Receiving Input from the User Using the Scanner library class.

• Sometimes we need to prompt the user during the execution of the program so that input is provided after a specific set of instructions has been executed.

• The previous technique of making the input part of the command to start the execution WILL NOT work then.

• We can provide this functionality by using the Scanner library class. The user can be prompted to enter data, after the program starts execution, via the keyboard. The Scanner object will read the characters typed on the keyboard.

24

Page 25: CS116 OBJECT ORIENTED PROGRAMMING II LECTURE 1 Part II GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology- George Koutsogiannakis.

Input Using the Scanner Class• Scanner class provides methods for reading byte,

short, int, long, float, double, and String data types from the Java console (keyboard) and other sources (like a file).

• Scanner parses (separates) input into sequences of characters called tokens.

• By default, tokens are separated by standard white space characters (tab, space, newline, etc.)

• i.e in the String “My name is Joe” there are 4 tokens. The first token is the substring “My” and so on.

25

Page 26: CS116 OBJECT ORIENTED PROGRAMMING II LECTURE 1 Part II GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology- George Koutsogiannakis.

A Scanner ConstructorScanner( InputStream source ) creates a Scanner object for reading from source. If source is System.in, this instantiates a Scanner object for reading from the Java console (keyboard).

(System.in is the keyboard)

Example: Scanner scan = new Scanner( System.in );

scan then is the object that we are going to use to read characters from the keyboard if System.in has been passed to the constructor of the Scanner class.The Scanner class has methods that help us capture the user ‘s input (as an example from the keyboard or a file).

26

Page 27: CS116 OBJECT ORIENTED PROGRAMMING II LECTURE 1 Part II GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology- George Koutsogiannakis.

Scanner class methods

• Some of the methods are listed in the next slide.

• Connect to the link for the java API http://java.sun.com/javase/7/docs/api/

and study the methods of Scanner class.

27

Page 28: CS116 OBJECT ORIENTED PROGRAMMING II LECTURE 1 Part II GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology- George Koutsogiannakis.

Scanner next… Methods

Return type Method name and argument list

dataType nextDataType( )

returns the next token in the input stream as a dataType. dataType can be byte, int, short, long, float, double, or boolean i.e nextDouble() or nextInt()

String next( )

returns the next token in the input stream as a String

String nextLine( )

returns the remainder of the line as a String

28

Page 29: CS116 OBJECT ORIENTED PROGRAMMING II LECTURE 1 Part II GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology- George Koutsogiannakis.

Prompting the User• The next… methods do not prompt the user for an input value• Use System.out.print to print the prompt, then call the next…

method

Example:1. Scanner scan = new Scanner( System.in );

2. System.out.print( "Enter your age > " );

3. int age = scan.nextInt( );

In this example the user program stops execution after statement 2 is executed. The program waits for the user to type something (a number in this case)

29

Page 30: CS116 OBJECT ORIENTED PROGRAMMING II LECTURE 1 Part II GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology- George Koutsogiannakis.

Prompting the User

On the DOS window we will see:C:\Users\George>java MyProgramPlease enter your age > _After the user enters a number (let us say that the user typed the number 19)

and presses the Enter key, the program resumes execution and line 3 is executed.

Line 3 reads what the user typed (19) as a String and at the same time converts it into an int data type. It assigns that data type (stores in memory) to the identifier age in this example.

From there on the program continues with the execution of other instructions. It is possible that we may want to stop the program further down again and ask the user to enter another input.

30

Page 31: CS116 OBJECT ORIENTED PROGRAMMING II LECTURE 1 Part II GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology- George Koutsogiannakis.

Scanner Example• Suppose that we want to read a String that a user of our program enters

on the keyboard:import java.util.Scanner;class UsingScanner {

public static void main(String[] args) {

Scanner scan =new Scanner(System.in);System.out.println("Enter a decimal number");String a=scan.next();double d=Double.parseDouble(a);System.out.println(d);

}}

31

Page 32: CS116 OBJECT ORIENTED PROGRAMMING II LECTURE 1 Part II GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology- George Koutsogiannakis.

Scanner Example

• Interpreting this program has the following outcome:

C:\CS115\Myexamples\ScannerExamples>java UsingScannerEnter a decimal number12.34The number you entered is:12.34• Notice that after the statement “Enter a decimal number” is displayed, the

program waits for the user to enter something on the keyboard.• Notice that the next action is for the user to type 12.34 on the keyboard.• The program then prints the last statement “The number you entered

is:12.34”

32

Page 33: CS116 OBJECT ORIENTED PROGRAMMING II LECTURE 1 Part II GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology- George Koutsogiannakis.

Scanner Example

• In the program the line: String a=scan.next();

captures whatever the user typed as a String data type (even if the user typed a number!)

• Our program converts the data type String represented by the identifier a to a double data type via the line:

double d=Double.parseDouble(a);

33

Page 34: CS116 OBJECT ORIENTED PROGRAMMING II LECTURE 1 Part II GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology- George Koutsogiannakis.

Wrapper Classes

• We can always convert a String to a primitive data type using classes called “Wrapper classes”.

In this example the class Double is the Wrapper class (notice that it is written with a capital D to differentiate it from the primitive data type double written with a lower case d).

• Its job is to convert a String to a double data type by invoking the method parseDouble that takes a primitive data type double as argument.

34

Page 35: CS116 OBJECT ORIENTED PROGRAMMING II LECTURE 1 Part II GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology- George Koutsogiannakis.

The Wrapper Classes

• “Wrap” the value of a primitive data type into an object

• Useful when methods require an object argument

• Also useful for converting Strings to an int or double

35

Page 36: CS116 OBJECT ORIENTED PROGRAMMING II LECTURE 1 Part II GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology- George Koutsogiannakis.

Wrapper Classes

Primitive Data Type Wrapper Class

double Double

float Float

long Long

int Integer

short Short

byte Byte

char Character

boolean Boolean

36

Page 37: CS116 OBJECT ORIENTED PROGRAMMING II LECTURE 1 Part II GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology- George Koutsogiannakis.

Back to Scanner

• We can capture the input from the keyboard directly as a numeric primitive data type instead of capturing it as a String first and then converting it (parsing it) to the particular numeric data type:

i.e. Scanner scan =new Scanner(System.in);

System.out.println("Enter a decimal number"); double a=scan.nextDouble();

37

Page 38: CS116 OBJECT ORIENTED PROGRAMMING II LECTURE 1 Part II GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology- George Koutsogiannakis.

Using the nextDouble method with Scanner object

import java.util.Scanner;class UsingScannerDouble {

public static void main(String[] args) {

Scanner scan =new Scanner(System.in);System.out.println("Enter a decimal number");double d=scan.nextDouble();System.out.println("The number you entered is:"+d);

}}Output: Enter a decimal numbner

13.456The number you entered is:13.456

38

Page 39: CS116 OBJECT ORIENTED PROGRAMMING II LECTURE 1 Part II GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology- George Koutsogiannakis.

Text Reading

• Continue reviewing Chapter 7.

39