cs 116 object oriented programming ii lecture 1 george koutsogiannakis 1 copyright: 2015 illinois...

61
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 1 GEORGE KOUTSOGIANNAKIS 1 ght: 2015 Illinois Institute of Technology/George Koutsogiannakis

Post on 21-Dec-2015

217 views

Category:

Documents


1 download

TRANSCRIPT

CS 116

OBJECT ORIENTED PROGRAMMING IILECTURE 1

GEORGE KOUTSOGIANNAKIS

1Copyright: 2015 Illinois Institute of Technology/George Koutsogiannakis

Administrative Information

• Instructor’s name: George Koutsogiannakis• Office : SB214• Office Hours: Mondays and Wednesdays

– No appointment is needed – 11:20 a.m. - 1:40 p.m. or – By appointment on another time frame.

• EMAIL: [email protected]• Phone: 312- 567 -5288

2

COURSE ADMINISTRATION

• COURSE WEB SITE: – http://www.cs.iit.edu/~cs116– Use it to get :

• Instructor’ s office hours• TAs office hours.• Access to extra credit practice exercises description

files.• Access to laboratories description files.• Access to the lecture presentations.

3

COURSE ADMINISTRATION

• Due dates for lab. assignments/exams.• Example code.• Solution to exercises, laboratories, quizzes, exams.• Information on grading policies.• Information on upcoming quizzes or exams.• Link available from Blackboard.

4

COURSE ADMINISTRATION

• BLACKBOARD– View your grades.– Submission of assignments:

• Go to your blackboard account then click on information• Choose assignment that you are submitting.• Only one submission is allowed per assignment. In case of errors

you have to email me so that I can approve a deletion and a resubmission.

• Zip the files that you are submitting by: Select files (or folders ) to be submitted

Right click the mouse and choose :sent to->Compressed (zipped) folder.

5

COURSE ADMINISTRATION• Be careful to submit under the assignment assignment. • Most common error: submitting an extra credit exercise under a

lab assignment and vice versa.

• Note: If you accessing the course web site from the Blackboard link , you need to refresh the browser every time.

6

COURSE ADMINISTRATIONcourse work

• Extra Credit Practice Exercises (8 assigned 5 needed to be submitted)– Shorter than labs. Single Task, emphasize a specific topic. Must be

done during class period on specified dates. They carry no grade until the end of the Semester. – Must be checked for correctness before submission by Instructor/TA– Submitted on Blackboard at the end of class period. No late

submissions are allowed. – Must be checked for correctness before submission by TA or myself.– If at least 5 out of 8 have been submitted (correctly done) an extra

credit of 5 points will be issued at the end of the Semester.– No credit will be issued if less than 5 are submitted.

7

COURSE ADMINISTRATIONcourse work

• Laboratories (9)– Multiple Tasks. Could cover more than one topic.– Start work on them in advance. Work on them in class on

the assigned date (as per the schedule). Finish outside of class and submit on Blackboard by the specified deadline,

– Ask questions in class.– Ask questions via emails to the instructor or the TA.– Do not hesitate to visit me in my office to ask questions.– To be done individually!!!– Total points awarded : 30

8

COURSE ADMINISTRATION

LAB GRADES

Lab 1: 2 points

Lab 2: 2 points

Lab 3: 2 points

Lab 4: 3 points

Lab 5: 3 points

Lab 6: 4 points

Lab 7: 4 points

Lab 8: 5 points

Lab 9: 5 points

TOTAL : 30 points

9

COURSE ADMINISTRATION

• Project (1)– To be done individually.– Description will be provided as per schedule.– Must submit source code and compiled files on

Blackboard by deadline.– 8 points

10

COURSE ADMINISTRATION

• SUBMISSION ON BLACKBOARD– Zip (do not RAR) all files for the particular assignment.– Name the zipped file as follows: firstName_lastName_AssignmentName.zipi.e John_Doe_InClassExercise1.zip Mary_Smith_Lab1.zip– Submit under the correct assignment folder in your Blackboard

account.– Ask for help if needed.

• Erroneous submissions need to be deleted by me first before a resubmission is allowed.

11

COURSE ADMINISTRATION

• Exams/Quizzes (2/2)– Closed Book/Closed Notes. Programming questions.– Must be done on a Text Editor, like Edit Plus, and submitted on

Blackboard. – Must submit source code and Compiled files.– Final Exam covers material from midterm to end of the Semester.– Midterm exam.: 20 points.– Final exam. : 30 points.– Quiz 1: 4 points– Quiz 2: 8 points.

12

Summary of Points

13

ASSIGNMENT NUMBER OF ASSIGNMNETS

POINTS FOR EACH

TOTAL POINTS

Extra Credit Practice Exercises

8 No grade until end of Semester

5 extra points if at least 5 are submitted correctly. (7 points if all 8 are submitted)

Labs 9 varies 30

Project 1 8 8

Quizzes 2 4/8 12

Exams 2 20/30 50

Total Points 100

.

COURSE ADMINISTRATION

• More on Submissions– Submissions for labs and exercises are not accepted after

the solution is posted on the course’s web site.– Quiz and Exams are also submitted on Blackboard at the

end of the allotted time on the day of the exam/quiz. • Make sure that you submit the files in the proper folder

named after the exam or the quiz.• Do not turn your station computer off until your

submission is verified by either the TA or the instructor.

14

COURSE ADMINISTRATION

• No laptops are allowed during exams or quizzes. Only the lab ‘ s station computers can be used.

• No flash drives are allowed in class during exams.

• No access to Internet or Email os allowed during exams.

15

COURSE ADMINISTRATION

• Teaching Assistants– You will be working with the same teaching assistant through the

Semester. Make sure that you know his/her name, office hours and email address (see the course web site for that information).

– For grading purposes you are assigned to a specific assistant.– Grading of exercises and labs is done by the TAs.– Grading of quizzes and exams is done by the instructor.– Learn the name and the email address of your Teaching Assistant. The

list will be published and posted on the web site at the end o fteh first week.

• You must participate in the course by asking questions either during the lectures or by visiting the instructor or teaching assistant during office hours.

16

ETHICS

• The following rules apply during a quiz or exam.– Violation of the items below will result in you having to drop the

course or receive a E grade for the course:• Opening the email service during the exam.• Opening another student’s blackboard account during the exam.• Accessing the internet without permission.• Having hard copies of solutions on your desk.• Using a flash drive during the test.• If you are sitting in front of computer terminal that has been left logged in

by a previous user you must turn it off and login again before you start the exam!

• If you get caught having access to files not created by you during the exam. and having obtaining then by any other means besides the aforementioned.

17

ETHICS

• Lab assignments are to be done individually.– The first two copying accusations will result in zero grade

for each assignment.– Any new attempt after that will result in getting an E grade

for the course.– Copying includes having obtained previous solutions of lab

assignments from students who took the course and resubmitting them!!!NOTE: Most lab assignments have changes from Semester to Semester in key

parts of the assignment. The TAs will be aware of the changes. Most students get caught by submitting the original solution thinking that it is the same!

18

CLASS ATTENDANCE1. Mandatory for freshman classes. Must sign in attendance sheet

otherwise you will be reported absent.2. During lectures material and solution could be distributed that will not

be posted on the web site. It is your responsibility to get a copy.3. During lectures you are not allowed to surf the internet.4. Class participation is encouraged in terms of questions, answers to

questions , working on impromptu exercises.

19

INFORMATION ON JAVA

• Web sites for Java material:– To download Java Development Kit for your own

computer (optional)• http://www.oracle.com/technetwork/java/javase/download

s/index.html • SE (Standard Edition) • Download JDK 7

– For online API AND TUTORIAL• http://docs.oracle.com/javase/7/docs/api/ For the Java API (Application Programming Interface)• http://docs.oracle.com/javase/tutorial/

20

INFORMATION ON JAVA

• See me if you need help with the tools needed for the course installations on your laptop!!

21

INFORMATION ON JAVATOOLS

• JDK– Java Development Kit- (Used when you write a

program)– Provides:

• The compiler• Other tools (not needed in this class)

• JRE– Java Runtime Environment- Used when you are ready

to execute (interpret) a program.– Provides:

• The runtime environment JVM (Java Virtual Machine) • The interpreter

22

INFORMATION ON JAVATOOLS

• Edit Plus or Notepad++– The text editor tool used by this class to write

(edit) java programs.• (note that there are other editors besides edit plus but

this one is the approved for the class).

– You can use other text editors as long as they don’t produce code.

– Notepad++ is free– EditPlus is not free.

23

INFORMATION ON JAVATOOLS

• Use text editor to write a program (i.e Notepad++)– Use Java API as help.– Use text and text examples for help. – Use class lectures and exercises done in class as

help.– The file with the code is referred to as the

“source code file”.

24

INFORMATION ON JAVATOOLS

– Note: There are text editors for MAC equivalent to Edit Plus for windows:• JEdit available at: www.jedit.org/

– Review how to compile command line. • If you need help on using command lien download the help

document available on the course’s web site :HELP DOCUMENT FOR COMPILING USING COMMAND LINE.

(practice following instructions).

25

Programming Styling

• When typing a Java program follow the guidelines as described in :

http://www.cwu.edu/~gellenbe/javastyle/ (cwu: Central Washington University)• Style refers to the way a Java program should be

typed in the source code file.

26

Style of a Java Program• Naming Conventions

»Variable Names»Constant Names»Method Names»Parameters Names

• Commenting»File Header Comments»Single-Line Comments»Trailing Comments

• Formatting»Indentation»White Space»Line Length

27

Topics in CS116

• Enumerations.• Packaging .• Sorting Algorithms.• Abstract Classes.• Abstract methods.• Method Overloading and Overriding.• Interfaces.• Inheritance.• Polymorphism.• Exceptions and User Defined Exceptions.

28

Topics in CS116

• IO Streams– Writing and reading text files.– Writing and reading binary coded files.– Writing and reading serializable objects into or from a file.

• Recursion.– Recursion with a single base case– Recursion with two base casses.

29

REVIEW OF OBJECT ORIENTED PROGRAMMING CONCEPTS.

30

• Service Class and Client Class.• Defining Instance Variables/static variables.• Writing Accessor/Mutator methods.• The toString and equals methods.• The Object Reference this.• static instance variables.• Static versus non static methods.

REVIEW OF OBJECT ORIENTED PROGRAMMING CONCEPTS.

• Providing input into a program:– Command Line input.– Keyboard input (using Scanner object).– Reading data from a file (Using Scanner object).

• Arrays of primitive data types.• Arrays of Objects.

31

CLASS

• Class– An abstract representation of a category or a

group.i.e. We can represent Students by creating a class called Student.

– Usually given a sentence , the nouns represent classes:

i.e. The student earned a grade of A Student will be a class. Grade can also be a class if we wanted.

32

CLASS

• Classes that the programmer creates are called:User Defined Classes.

• Classes that are part of the Java Library of classes are called: Pre Defined Classes.– Notice that a pre defined class is also a class that someone

has already created and made available for us to use.– Pre Defined Library classes are described in the API– The API is available online.

33

User-Defined Classes

34

• Combine data and the methods that operate on the data.

• A service class defines the category of data (i.e. Student class).

• A Client Classes can use one or more service classes.

Service (Template classes)

• Advantages:– The class methods are responsible for the validity of

the data– Implementation details can be hidden– The class can be reused.– Does not need a main method.

35

Service (Template classes)

• StructureInstance variables.Default and non default constructors.Accessor and mutator methods.toString method.Equals method.Other help methods as required.

36

Client Classes

• Client of a Service class(classes) i.e ClientStudent class). Needs a main method.– A program that instantiates objects and calls (invokes) the

methods of the Service class (or classes) in its main method.

– In the main method we can instantiate an object of the Client class and use it to invoke not static methods of the Client class.

– We can make direct calls to its static methods (without an object).

37

Syntax for Defining a Class

38

accessModifier class ClassName{ // class definition goes here}

***Note that the curly braces are required. i.epublic class Student{// class definition goes here

}

Client Class

• public class ClientStudent { //must have a main method (plus other methods also).

//we would instantiate Student service class //objects in the method(s) of this class.

//Use objects to invoke methods or access fields //of the Service class Student.

}

39

Class-Important Terminology

40

• Fields – instance variables: the data for each object– class data: static data that all objects share– Visible by all methods of the class.

• Members – fields and methods

• Access Modifier– determines access rights for the class and its members– defines where the class and its members can be used

Class Access Modifiers

41

Access Modifier Class or member can be referenced by…

public methods of the same class and methods of other classes

private methods of the same class only

protected methods of the same class, methods of subclasses (this term will be explained later on in the course), and methods of classes in the same package

No access modifier (package access)

methods in classes belonging to the same package as the class we are trying to reference only

Class-What is a Package?• Classes can reside in packages

– Library (pre defined classes) reside in packages i.e. import java.util.Scanner;

Scanner class is in package: java.util– Notice that a package is actually a directory path where the .class files

are located.• We can create a package for our user defined classes also. We will

learn how to do that shortly in the course. • Some editors, like Eclipse, can create packages for our programs.

We will learn how to incorporate the code manually in our programs using the proper keywords in the code and compiling command line.(if you don’t know how to compile command line follow the tutorial I have available on the course’s web site).

42

Defining Instance Variables

Syntax: accessModifier dataType identifierList;

dataType can be primitive date type or a class typeidentifierList can contain:

– one or more variable names of the same data type– multiple variable names separated by commas– initial values

• Instance variables can be declared as final

43

Examples of Instance Variable Definitions

private String name = "";

private final int PERFECT_SCORE = 100,

PASSING_SCORE = 60;

private int startX, startY,width,height;

44

Primitive Data Types

45

primitive

integral boolean floating point

float doublebyte char short int long

Note: A String is not a primitive data type but rather a pre defined class object

SOFTWARE ENGINEERING TIP

Define instance variables for the data that all objects will have in common.

Define instance variables as private so that only the methods of the class will be able to set or change their values.

Begin the instance variable identifier with a lowercase letter and capitalize internal words.

46

The Auto Class

public class Auto{ private String model;

private int milesDriven; private double gallonsOfGas; } The Auto class has three instance variables: model,

milesDriven and gallonsOfGas.

47

Static Instance Variables• Also called class variables • One copy of a static variable is created per class• static variables are not associated with an object• static constants are often declared as public• To define a static variable, include the keyword

static in its definition:Syntax: accessSpecifier static dataType variableName…;Example: public static int countAutos = 0;

48

Static Instance Variables

• Every instance of the class (object) can see the same value of the static variable (the latest value assigned to that variable).

• If an object modifies the value of the static variable then all objects of that class see the new value.

49

Class Members

• A class has– Instance variables (also called global variables

sometimes).– Constructors

• Default- has no arguments. Initializes the instance variables to pre determined value (i.e. zero, “ “, etc).

• Non default- has arguments. Initializes the instance variables to values passed in the arguments.

– Methods • One of the methods is a main method if the class is a

client class.

50

Accessor/Mutator methods

• Accessor methods– return the value of an instance variable i.e. public String getModel()

{return model;

}

51

Accessor/Mutator methods

• Mutator methods – Set the value of an instance variable

i.e. public void setModel (String mod) {

model=mod; }

52

To String method• Often classes have a toString method that

outputs the values of its instance variables.

public String toString(){

String output=“The value of model is”+model+”\n”+”The miles driven:”+milesDriven………..etc…..”);

return output;}

53

Creating Objects of a class

• Classes are a template used to create specific objects

• An object of a class is created by using the new operator and calling one of the constructors of the class:i.e. Auto car1=new Auto();

or Auto car2=new Auto(String bmw, int 1000,

int 20);

54

Comparing Objects For Equality

• Objects of the same class can be compared for equality.• The definition of the term equality is up to the programmer:

– i.e Suppose we have class Student with instance variables as shown public class Student

{ String firstName=“ “;

String lastName=“ “; int StudentID=0; String address=“ “; ……………………………………………. ……………………………………………..

55

Comparing Objects For Equality

• We may decide that two Student objects are equal if and only if the studentID instance variable has the same value for both objects (regardless if the rest of the instance variables have the same values or not).

• We create a method called equals to test for the equality of two objects of the same class.

56

Comparing Objects For Equality

• Example code for equals method to be included in Student class:

public boolean equals (Student st) {

if(this.getStudentID()==st.getStudentID()) return true; else

return false; }

57

Comparing Objects For Equality• In the client class that uses Student we can make

comparisons of Student objects: public class StudentClient {

public static void main(String [] args) { Student st=new Student(“George”, “Kay”, 1234, “654 somestreet”);

Student st1=new Student(“Nicholas”, “Jones”, 1234, “654 somestreet”);

boolean b= st.equals(st1); if(b==true)

System.out.println(“They are equal”); else

System.out.println(“They are NOT re equal”); }} 58

Comparing Objects For Equality

• Notice that in the equals method this refers to object st that invokes the equals method.

59

Terminology• Object reference: identifier of the object. The name we

used for the object.• Object data: The data encaptulated by a specific object

(reference). The values of the instance variables as pertained to that specific object.i. e. If we create a Student template class then a specific object reference called st may have such data as:firstName=“John”

lastName=“Doe”• Instantiating an object: creating an object of a class by

using the new operator.• Instance of the class: the object we created.• Methods: the code to manipulate the object data.• Calling a method: invoking a service for an object.

60

Study Guide

• Review concepts from CS115 material Read from your text book :– chapter 7

• Sections 7.1-7.8 and 7.10-7.11

61