Day 2. COMP 1006/1406A Summer M. Jason Hinek Carleton University

Similar documents
Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University

Day 3. COMP 1006/1406A Summer M. Jason Hinek Carleton University

Day 5. COMP1006/1406 Summer M. Jason Hinek Carleton University

Lecture 2. COMP1406/1006 (the Java course) Fall M. Jason Hinek Carleton University

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

Introduction to Programming Using Java (98-388)

Java Object Oriented Design. CSC207 Fall 2014

Java Bytecode (binary file)

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

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

CS 231 Data Structures and Algorithms, Fall 2016

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

Java Fundamentals (II)

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Program Fundamentals

OOPs Concepts. 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8.

Chapter 4 Defining Classes I

CSC207H: Software Design. Java + OOP. CSC207 Winter 2018

CS-202 Introduction to Object Oriented Programming

Distributed Systems Recitation 1. Tamim Jabban

Object Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia

Principles of Object Oriented Programming. Lecture 4

Lecture 6. COMP1006/1406 (the OOP course) Summer M. Jason Hinek Carleton University

CSC207H: Software Design. Java + OOP. CSC207 Winter 2018

CS 11 java track: lecture 1

Atelier Java - J1. Marwan Burelle. EPITA Première Année Cycle Ingénieur.

Super-Classes and sub-classes

Subclass Gist Example: Chess Super Keyword Shadowing Overriding Why? L10 - Polymorphism and Abstract Classes The Four Principles of Object Oriented

COP 3330 Final Exam Review

WA1278 Introduction to Java Using Eclipse

CS260 Intro to Java & Android 03.Java Language Basics

CHAPTER 7 OBJECTS AND CLASSES

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

1 Shyam sir JAVA Notes

Computer Science II (20073) Week 1: Review and Inheritance

CHAPTER 7 OBJECTS AND CLASSES

1B1b Classes in Java Part I

Reviewing for the Midterm Covers chapters 1 to 5, 7 to 9. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

Programming Language Concepts: Lecture 2

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Programming overview

CS304 Object Oriented Programming Final Term

Outline. Overview. Control statements. Classes and methods. history and advantage how to: program, compile and execute 8 data types 3 types of errors

Java Magistère BFA

C08: Inheritance and Polymorphism

Java: introduction to object-oriented features

CS 251 Intermediate Programming Inheritance

Getting started with Java

JAVA: A Primer. By: Amrita Rajagopal

Data Structures (list, dictionary, tuples, sets, strings)

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods

What are the characteristics of Object Oriented programming language?

Programming Language Concepts: Lecture 2

+ Inheritance. Sometimes we need to create new more specialized types that are similar to types we have already created.

Selected Java Topics

Inheritance (Part 5) Odds and ends

Topic 3 Encapsulation - Implementing Classes

Chapter 1 Getting Started

COMP 250 Fall inheritance Nov. 17, 2017

Index COPYRIGHTED MATERIAL

Day 6. COMP1006/1406 Summer M. Jason Hinek Carleton University

13 th Windsor Regional Secondary School Computer Programming Competition

CMSC 132: Object-Oriented Programming II

Programming II (CS300)

Computer Components. Software{ User Programs. Operating System. Hardware


Programming II (CS300)

Lecture 1 - Introduction (Class Notes)

Inheritance and Polymorphism

Big software. code reuse: The practice of writing program code once and using it in many contexts.

Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II

Object Oriented Programming

Chapter 6 Introduction to Defining Classes

Abstract Classes and Interfaces

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

Administration. Classes. Objects Part II. Agenda. Review: Object References. Object Aliases. CS 99 Summer 2000 Michael Clarkson Lecture 7

Building custom components IAT351

Lecture 02, Fall 2018 Friday September 7

Distributed Systems Recitation 1. Tamim Jabban

Classes, objects, methods and properties

PROGRAMMING III OOP. JAVA LANGUAGE COURSE

CompSci 125 Lecture 02

What is Inheritance?

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and More

THE CONCEPT OF OBJECT

Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L

Introduction to Inheritance

The class Object. Lecture CS1122 Summer 2008

Carleton University COMP1406/1006, Summer 2013 Tutorial 2

COMP 250 Winter 2011 Reading: Java background January 5, 2011

Chapter 11. Categories of languages that support OOP: 1. OOP support is added to an existing language

CMSC 341. Nilanjan Banerjee

Lecture Notes CPSC 224 (Spring 2012) Today... Java basics. S. Bowers 1 of 8

CS 177 Recitation. Week 1 Intro to Java

Basic Object-Oriented Concepts. 5-Oct-17

Defining Classes and Methods

Informatik II (D-ITET) Tutorial 6

Transcription:

Day 2 COMP 1006/1406A Summer 2016 M. Jason Hinek Carleton University

today s agenda a quick look back (Monday s class) assignments a1 is due on Monday a2 will be available on Monday and is due the following Monday testing black box and white box testing problem solving More Java Classes/Objects 2

last time... primitive data types byte, short, int, long (integers) float, double (approximate real numbers) boolean (logical true/false) char (unicode characters) type conversions automatic, cast operators (type), methods order of operations for example, array access [ ] > unary negation - > cast ( ) > multiplication * 3

last time... primitive data types byte, short, int, long (integers) float, double (approximate real numbers) boolean (logical true/false) char (unicode characters) type conversions automatic, cast operators (type), methods order of operations for example, array access [ ] > unary negation - > cast ( ) > multiplication * aside: what do the following lines do? boolean b = false; b true; if( b = true ) System.out.println("hi"); 3

last time... reference data types (objects) everything that isn t a primitive data type new operator allocates memory for objects memory model primitive data type variables store actual values (data) everythign else stores reference to actual object (or null) it gets messy... 4

last time... /* hello world */ public class HelloWorld{ public static void main(string[] args){ System.out.println("hello, world!"); } } access modifier public top level access modifier specifies who can see HelloWorld member level access modifier specifies who can access main (non access) modifier static allows a method to be called without an instance of the class return type void it is a Java keyword that tells us that a method returns nothing it is not an actual Java type System.out System is a class with three attributes/fields in, out and err out is a PrintStream object, it is standard output println is a method of out 5

last time... /* hello world */ public class HelloWorld{ public static void main(string[] args){ System.out.println("hello, world!"); } } what do we know about System.out.println()? 6

last time... /* hello world */ public class HelloWorld{ public static void main(string[] args){ System.out.println("hello, world!"); } } what do we know about System.out.println()? we can look at the API for the System class <link> API - application programming interface specifies how to use a given class 6

running hello world /* Java hello world */ public class HelloWorld{ public static void main(string[] args){ System.out.println("hello, world!"); } } Java convention is that class name is capitalized (use camel case if more than one word) class XXX must be in the file XXX.java so HellowWorld must be in the file HelloWorld.java first we need to compile the source code into Java bytecode IDE will have a compile button javac HelloWorld.java from console window (shell) this creates HelloWorld.class, which is the Java bytecode next, we run the bytecode in the JVM (Java virtual machine) java HelloWorld from the console window runs out program! the JVM executes the main method of our program 7

What we didn t get to... 8

Abstraction In software engineering and computer science, abstraction is a technique for managing complexity of computer systems. It works by establishing a level of complexity on which a person interacts with the system, suppressing the more complex details below the current level. -wikipedia 9

Abstraction In software engineering and computer science, abstraction is a technique for managing complexity of computer systems. It works by establishing a level of complexity on which a person interacts with the system, suppressing the more complex details below the current level. -wikipedia hardware 9

Abstraction In software engineering and computer science, abstraction is a technique for managing complexity of computer systems. It works by establishing a level of complexity on which a person interacts with the system, suppressing the more complex details below the current level. -wikipedia machine language hardware 9

Abstraction In software engineering and computer science, abstraction is a technique for managing complexity of computer systems. It works by establishing a level of complexity on which a person interacts with the system, suppressing the more complex details below the current level. -wikipedia assembly language machine language hardware 9

Abstraction In software engineering and computer science, abstraction is a technique for managing complexity of computer systems. It works by establishing a level of complexity on which a person interacts with the system, suppressing the more complex details below the current level. -wikipedia Java assembly language machine language hardware 9

Abstraction A first step in abstraction for us is the notion of a procedure procedure function method subroutine A procedure is a sequence of instructions (statements) that performs a specific task. 10

Abstraction A first step in abstraction for us is the notion of a procedure procedure function method subroutine A procedure is a sequence of instructions (statements) that performs a specific task. Math.sin(0.172) computes the sine of 0.172 radians. We don t really care how it does it, we just care that it gives us the right value. System.out.println("hi") prints the characters h and i to the screen. How does this actually happen? Do we care how it happens? 10

Procedural programming program is a sequence of function calls helps us write structured programs this helps us write better programs (Software Engineering) code that does one thing is grouped into a procedure (function/method) helps us achieve modularization code that is repeated during the execution of the program is put in a procedure (function/method) lets us write less code (less testing and maintenance!)) You have already been doing this in COMP1005/1405. 11

Procedural programming public class Game{ static int updategame(int lives){...} static boolean checkcontinue(){...} static void updategraphics(){..} } public static void main(string[] args){ int lives = 3; boolean keepplaying = true; while(lives > 0 && keepplaying){ lives = updategame(lives); keepplaying = checkcontinue(); updategraphics(); } } 12

Procedural programming In Java, procedural programming involves writing and using a collection of static functions You will most likely still use objects when writing code in this style in Java arrays are objects strings are objects 13

command line arguments vs user input both are ways of providing some information to your program command line arguments input is entered before program runs input is passed as parameters to main method (args) (not practical for many user inputs) ((very useful for testing)) user input input is entered while program is running standard input is the keyboard (very flexible and useful) 14

Some Java classes Let s take a quick look at some classes that Java provides https://docs.oracle.com/javase/8/docs/api/java/lang/math.html https://docs.oracle.com/javase/8/docs/api/java/lang/string.html https://docs.oracle.com/javase/8/docs/api/java/util/scanner.html Anything found in java.lang is always visible to your program. Using scanner we need to import the class. 15

Some Java classes Let s take a quick look at some classes that Java provides https://docs.oracle.com/javase/8/docs/api/java/lang/math.html https://docs.oracle.com/javase/8/docs/api/java/lang/string.html https://docs.oracle.com/javase/8/docs/api/java/util/scanner.html Anything found in java.lang is always visible to your program. Using scanner we need to import the class. 15

let s take a break... for 5 minutes 16

testing 17

Testing how do you know if your code is correct? 18

Testing how do you know if your code is correct? it compiled 18

Testing how do you know if your code is correct? it compiled it ran without an error 18

Testing how do you know if your code is correct? it compiled it ran without an error it gave the same result as the example in the assignment 18

Testing how do you know if your code is correct? it compiled it ran without an error it gave the same result as the example in the assignment what does this really mean though? 18

Testing how do you know if your code is correct? it compiled it ran without an error it gave the same result as the example in the assignment what does this really mean though? 19

Testing how do you know if your code is correct? it compiled if it did not compile it is not correct code it ran without an error it gave the same result as the example in the assignment what does this really mean though? 19

Testing how do you know if your code is correct? it compiled if it did not compile it is not correct code it ran without an error if there was a runtime error it is not correct/robust code it gave the same result as the example in the assignment what does this really mean though? 19

Testing how do you know if your code is correct? it compiled if it did not compile it is not correct code it ran without an error if there was a runtime error it is not correct/robust code it gave the same result as the example in the assignment if the output is different from assignment example what does this really mean though? 19

Testing how do you know if your code is correct? it compiled if it did not compile it is not correct code it ran without an error if there was a runtime error it is not correct/robust code it gave the same result as the example in the assignment if the output is different from assignment example??? what does this really mean though? 19

Testing how do you know if your code is correct? 20

Testing how do you know if your code is correct? need to try all possible inputs to program 20

Testing how do you know if your code is correct? need to try all possible inputs to program consider input of a single int (32-bits) how many possible inputs are there? 20

Testing how do you know if your code is correct? need to try all possible inputs to program consider input of a single int (32-bits) how many possible inputs are there? (4,294,967,296) 20

Testing how do you know if your code is correct? need to try all possible inputs to program consider input of a single int (32-bits) how many possible inputs are there? (4,294,967,296) what happens when there are two integers? 20

Testing how do you know if your code is correct? need to try all possible inputs to program consider input of a single int (32-bits) how many possible inputs are there? (4,294,967,296) what happens when there are two integers? (18,446,744,073,709,551,616) 20

Testing how do you know if your code is correct? need to try all possible inputs to program consider input of a single int (32-bits) how many possible inputs are there? (4,294,967,296) what happens when there are two integers? (18,446,744,073,709,551,616) in general, this is not feasible for even simple programs... 20

Testing how do you know if your code is correct? need to try all possible inputs to program consider input of a single int (32-bits) how many possible inputs are there? (4,294,967,296) what happens when there are two integers? (18,446,744,073,709,551,616) in general, this is not feasible for even simple programs... prove that it is correct 20

Testing how do you know if your code is correct? need to try all possible inputs to program consider input of a single int (32-bits) how many possible inputs are there? (4,294,967,296) what happens when there are two integers? (18,446,744,073,709,551,616) in general, this is not feasible for even simple programs... prove that it is correct formal methods is an entire research field devoted to this way beyond the scope of this course! 20

Testing how do you know if your code is correct? need to try all possible inputs to program consider input of a single int (32-bits) how many possible inputs are there? (4,294,967,296) what happens when there are two integers? (18,446,744,073,709,551,616) in general, this is not feasible for even simple programs... prove that it is correct formal methods is an entire research field devoted to this way beyond the scope of this course! in reality, we just don t know 20

Testing how do you know if your code is correct? need to try all possible inputs to program consider input of a single int (32-bits) how many possible inputs are there? (4,294,967,296) what happens when there are two integers? (18,446,744,073,709,551,616) in general, this is not feasible for even simple programs... prove that it is correct formal methods is an entire research field devoted to this way beyond the scope of this course! in reality, we just don t know we can have confidence that the code is relatively bug free test, test and test... 20

Testing how do you know if your code is correct? need to try all possible inputs to program consider input of a single int (32-bits) how many possible inputs are there? (4,294,967,296) what happens when there are two integers? (18,446,744,073,709,551,616) in general, this is not feasible for even simple programs... prove that it is correct formal methods is an entire research field devoted to this way beyond the scope of this course! in reality, we just don t know we can have confidence that the code is relatively bug free test, test and test... but let s put some thought into the tests! reduce the number of redundant tests! only use good tests 20

Testing consider two types of testing 21

Testing consider two types of testing black box testing 21

Testing consider two types of testing black box testing white box testing (clear box testing) 21

Black box testing no details of data structures known no details of algorithms used but, we do have access to the interface (API for Java classes) 22

Black box testing no details of data structures known no details of algorithms used but, we do have access to the interface (API for Java classes) interface is like a contract between code writer and code user 22

Black box testing no details of data structures known no details of algorithms used but, we do have access to the interface (API for Java classes) interface is like a contract between code writer and code user we have contracts for methods in class 22

Black box testing no details of data structures known no details of algorithms used but, we do have access to the interface (API for Java classes) interface is like a contract between code writer and code user we have contracts for methods in class will construct test cases based on the contracts 22

Black box testing boolean greaterthan10(int n): greaterthan10 : int -> boolean purpose: determine if n is greater than 10 preconditions: n is a non-negative integer postconditions: outputs true if n > 10 outputs false if n <= 10 23

Black box testing boolean greaterthan10(int n): greaterthan10 : int -> boolean purpose: determine if n is greater than 10 preconditions: n is a non-negative integer postconditions: outputs true if n > 10 outputs false if n <= 10 what do the pre- and post-conditions tell us? 23

Black box testing boolean greaterthan10(int n): greaterthan10 : int -> boolean purpose: determine if n is greater than 10 preconditions: n is a non-negative integer postconditions: outputs true if n > 10 outputs false if n <= 10 what do the pre- and post-conditions tell us? special cases? 23

Black box testing boolean greaterthan10million(int n): greaterthan10million : int -> boolean purpose: determine if n is greater than 10 milion preconditions: n is a non-negative integer postconditions: outputs true if n > 10 million outputs false if n <= 10 million what do the pre- and post-conditions tell us? special cases? 24

Black box testing boolean greater(int a, int b): greater : int int -> boolean purpose: determine if a is greater than b preconditions: a is a non-negative integer b is an integer postconditions: outputs true if a > b outputs false if a <= b 25

Black box testing boolean greater(int a, int b): greater : int int -> boolean purpose: determine if a is greater than b preconditions: a is a non-negative integer b is an integer postconditions: outputs true if a > b outputs false if a <= b what do the pre- and postconditions tell us? 25

Black box testing boolean greater(int a, int b): greater : int int -> boolean purpose: determine if a is greater than b preconditions: a is a non-negative integer b is an integer postconditions: outputs true if a > b outputs false if a <= b what do the pre- and postconditions tell us? special cases? 25

Black box testing Test the contract boundary cases near-boundary cases (off-by-one error?) extreme cases (does the program scale?) special cases (program dependent, all of the above) typical/average cases 26

Black box testing test each method individually test methods interacting with each other test entire program 27

White box testing Test the code we have knowledge of data structures used we have details of algorithms used we may have the actual code 28

White box testing Test the code we have knowledge of data structures used we have details of algorithms used we may have the actual code (assume this) test each branch in the method / program 28

White box testing Test the code we have knowledge of data structures used we have details of algorithms used we may have the actual code (assume this) test each branch in the method / program have each line of code in at least one test 28

White box testing Test the code we have knowledge of data structures used we have details of algorithms used we may have the actual code (assume this) test each branch in the method / program have each line of code in at least one test use same approach as black box testing 28

let s take a break... for 5 minutes 29

30

Problem Solving George Pólya How to Solve it Terminology: data, unknown, condition 31

Problem Solving Using the given data to find the unknown such that the condition is satisfied. the data is the information you have. the unknown is the information you want. the condition is the constraints on the problem. These are rules (often implicit) that must be followed. Alternatively... Using the given data to achieve a goal such that the condition is satisfied. Using the given data to create an algorithm/program that achieves a goal such that the constraints are satisfied. 32

Problem Solving The four phases of problem solving 1. Understand the problem. identify the data/unknown/condition 2. Devise a plan. choose a technique/heuristic/approach start over if needed 3. Carry out the plan. 4. Look back. execute your plan check each step start over if needed reflect on what you did start over if needed 33

Problem Solving General strategies Related problems Abstraction transform the problem into one you already know how to solve remove details that are not relevant to the problem Divide and Conquer break the problem into (smaller) sub-problems Backward Chaining start from the solution and work backwards 34

Problem Solving General strategies (from Think Like a Programmer, V. A. Spraul) Always have a plan Restate the problem Break the problem down Start with what you know Reduce the problem Look for analogies Experiment Don t get frustrated! 35

Problem Solving General strategies (from Think Like a Programmer, V. A. Spraul) Always have a plan Aimless wandering wastes time. Without a plan, you are hoping for a lucky break. Plans give you intermediate goals. Plans can change. Restate the problem Check out the problem from every angle before starting. We may find the goal is not what we thought. Use restatement to confirm understanding. Break the problem down Divide the problem into steps or phases. Difficulty for each phase can be an order of magnitude lower. Sometimes the sub-problems are hidden. 36

Problem Solving General strategies (from Think Like a Programmer, V. A. Spraul) Start with what you know Fully investigate a problem with the skills you have first. Build confidence and momentum towards your goal. You may learn more about the problem this way. Reduce the problem Reduce scope by adding or removing constraints. Work on a simpler problem that isn t easily divided. Pinpoint where remaining difficulties lie. Look for analogies Look for similarities to problems you ve already solved. Recognizing analogies improves speed and skill. You need to build up a store of prior problems before you can find analogies. 37

Problem Solving General strategies (from Think Like a Programmer, V. A. Spraul) Experiment Try things and observe the results (this is not guessing!). Trial-and-error is a valid approach to problem solving (not to be confused with guessing) Make small test programs. Don t get frustrated Everything will seem to take longer and be harder! Avoiding frustration is a decision you make. Go back to the plan, work on a different problem, or take a break. 38

Problem Solving General strategies (from Think Like a Programmer, V. A. Spraul) Experiment Try things and observe the results (this is not guessing!). Trial-and-error is a valid approach to problem solving (not to be confused with guessing) Make small test programs. Don t get frustrated Everything will seem to take longer and be harder! Avoiding frustration is a decision you make. Go back to the plan, work on a different problem, or take a break. 38

39

software engineering There is no one single best way of writing code 40

software engineering There is no one single best way of writing code small program (HelloWorld) 40

software engineering There is no one single best way of writing code small program (HelloWorld) main method sequence of statements 40

software engineering There is no one single best way of writing code small program (HelloWorld) main method sequence of statements bigger programs 40

software engineering There is no one single best way of writing code small program (HelloWorld) main method sequence of statements bigger programs reduce duplicate code with methods (functions) collect data together (arrays) 40

software engineering There is no one single best way of writing code small program (HelloWorld) main method sequence of statements bigger programs reduce duplicate code with methods (functions) collect data together (arrays) modular programming 40

software engineering There is no one single best way of writing code small program (HelloWorld) main method sequence of statements bigger programs reduce duplicate code with methods (functions) collect data together (arrays) modular programming break up program into modules each has independent functionality 40

software engineering There is no one single best way of writing code small program (HelloWorld) main method sequence of statements bigger programs reduce duplicate code with methods (functions) collect data together (arrays) modular programming break up program into modules each has independent functionality procedural programming 40

software engineering There is no one single best way of writing code small program (HelloWorld) main method sequence of statements bigger programs reduce duplicate code with methods (functions) collect data together (arrays) modular programming break up program into modules each has independent functionality procedural programming a sequence of procedure calls that modify the state Basic, Pascal, Fotran, C 40

software engineering There is no one single best way of writing code small program (HelloWorld) main method sequence of statements bigger programs reduce duplicate code with methods (functions) collect data together (arrays) modular programming break up program into modules each has independent functionality procedural programming a sequence of procedure calls that modify the state Basic, Pascal, Fotran, C, Java, C++ 40

software engineering There is no one single best way of writing code small program (HelloWorld) main method sequence of statements bigger programs reduce duplicate code with methods (functions) collect data together (arrays) modular programming break up program into modules each has independent functionality procedural programming a sequence of procedure calls that modify the state Basic, Pascal, Fotran, C, Java, C++ object oriented programming 40

software engineering There is no one single best way of writing code small program (HelloWorld) main method sequence of statements bigger programs reduce duplicate code with methods (functions) collect data together (arrays) modular programming break up program into modules (classes in Java) each has independent functionality procedural programming a sequence of procedure calls that modify the state Basic, Pascal, Fotran, C, Java, C++ object oriented programming a collection of interacting objects 40

software engineering There is no one single best way of writing code small program (HelloWorld) main method sequence of statements bigger programs reduce duplicate code with methods (functions) collect data together (arrays) modular programming break up program into modules (classes in Java) each has independent functionality procedural programming a sequence of procedure calls that modify the state Basic, Pascal, Fotran, C, Java, C++ object oriented programming a collection of interacting objects objects have both state and behaviour 40

software engineering large projects are very complex 41

software engineering large projects are very complex humans are not perfect... 41

software engineering large projects are very complex humans are not perfect... we make mistakes when solving complex problems 41

software engineering large projects are very complex humans are not perfect... we make mistakes when solving complex problems we make mistakes because we are lazy 41

software engineering large projects are very complex humans are not perfect... we make mistakes when solving complex problems we make mistakes because we are lazy we cheat when we can 41

software engineering large projects are very complex humans are not perfect... we make mistakes when solving complex problems we make mistakes because we are lazy we cheat when we can how can we reduce the impacts humans have on code? 41

software engineering large projects are very complex humans are not perfect... we make mistakes when solving complex problems we make mistakes because we are lazy we cheat when we can how can we reduce the impacts humans have on code? write less code 41

software engineering large projects are very complex humans are not perfect... we make mistakes when solving complex problems we make mistakes because we are lazy we cheat when we can how can we reduce the impacts humans have on code? write less code prevent cheating 41

software engineering large projects are very complex humans are not perfect... we make mistakes when solving complex problems we make mistakes because we are lazy we cheat when we can how can we reduce the impacts humans have on code? write less code prevent cheating simplify the complexity (abstraction) 41

procedural programming data structures hold data (state of the program) a main method provides coarse-grain control flow for program program is a sequence of procedure calls that modify the state each procedure should do one thing (modularization) 42

procedural programming data structures hold data (state of the program) a main method provides coarse-grain control flow for program program is a sequence of procedure calls that modify the state each procedure should do one thing (modularization) why might we want to program like this? 42

procedural programming data structures hold data (state of the program) a main method provides coarse-grain control flow for program program is a sequence of procedure calls that modify the state each procedure should do one thing (modularization) why might we want to program like this? code is easier for us to read 42

procedural programming data structures hold data (state of the program) a main method provides coarse-grain control flow for program program is a sequence of procedure calls that modify the state each procedure should do one thing (modularization) why might we want to program like this? code is easier for us to read code is easier to test/debug 42

procedural programming data structures hold data (state of the program) a main method provides coarse-grain control flow for program program is a sequence of procedure calls that modify the state each procedure should do one thing (modularization) why might we want to program like this? code is easier for us to read code is easier to test/debug code is easier for others to read 42

procedural programming data structures hold data (state of the program) a main method provides coarse-grain control flow for program program is a sequence of procedure calls that modify the state each procedure should do one thing (modularization) why might we want to program like this? code is easier for us to read saves us time developing/maintaining/upgrading code code is easier to test/debug saves us time developing/maintaining/upgrading code code is easier for others to read saves us time developing/maintaining/upgrading code 42

procedural programming data structures hold data (state of the program) a main method provides coarse-grain control flow for program program is a sequence of procedure calls that modify the state each procedure should do one thing (modularization) why might we want to program like this? code is easier for us to read saves us time developing/maintaining/upgrading code saves us money, time and our sanity code is easier to test/debug saves us time developing/maintaining/upgrading code saves us money, time and our sanity code is easier for others to read saves us time developing/maintaining/upgrading code saves us money, time and our sanity 42

object oriented programming (OOP) a different approach to programming that focuses on objects interacting with each other (passing messages to each other) three principles of object oriented programming: encapsulation - objects combine both data and operations on the data - objects have both state and behaviour inheritance - classes inherit data and operations from other classes polymorphism - objects can act like other objects. dynamic binding allows objects to determine which methods to use at runtime. 43

object oriented programming (OOP) a different approach to programming that focuses on objects interacting with each other (passing messages to each other) three principles of object oriented programming: encapsulation - objects combine both data and operations on the data - objects have both state and behaviour - allows us to model very complex real-world problems nicely inheritance - classes inherit data and operations from other classes - promotes code sharing and re-usability (write less code!) - [intuitive] hierarchical code organization polymorphism - objects can act like other objects. dynamic binding allows objects to determine which methods to use at runtime. - simplifies code understanding - standardizes method naming 43

object oriented programming (OOP) a different approach to programming that focuses on objects interacting with each other (passing messages to each other) three principles of object oriented programming: encapsulation - objects combine both data and operations on the data - objects have both state and behaviour - allows us to model very complex real-world problems nicely inheritance - classes inherit data and operations from other classes - promotes code sharing and re-usability (write less code!) - [intuitive] hierarchical code organization polymorphism - objects can act like other objects. dynamic binding allows objects to determine which methods to use at runtime. - simplifies code understanding - standardizes method naming OOP shines in BIG projects (don t be discouraged if it seems like a lot of work at first) 43

classes and objects data type is a set of values and a set of operations defined on those values 44

classes and objects data type is a set of values and a set of operations defined on those values int the integers 2,147,483,648 2,147,483,647 +, -, *, /, %, <, >, <=,... 44

classes and objects data type is a set of values and a set of operations defined on those values int the integers 2,147,483,648 2,147,483,647 +, -, *, /, %, <, >, <=,... String sequence of zero or more characters + (concatenation), toupper(), etc 44

classes and objects data type is a set of values and a set of operations defined on those values int the integers 2,147,483,648 2,147,483,647 +, -, *, /, %, <, >, <=,... String sequence of zero or more characters + (concatenation), toupper(), etc Java has 8 primitive data types 44

classes and objects data type is a set of values and a set of operations defined on those values int the integers 2,147,483,648 2,147,483,647 +, -, *, /, %, <, >, <=,... String sequence of zero or more characters + (concatenation), toupper(), etc Java has 8 primitive data types Many non-primitive data types are available (String, Date, etc) 44

classes and objects data type is a set of values and a set of operations defined on those values int the integers 2,147,483,648 2,147,483,647 +, -, *, /, %, <, >, <=,... String sequence of zero or more characters + (concatenation), toupper(), etc Java has 8 primitive data types Many non-primitive data types are available (String, Date, etc) Java allows us to make our own data types each class is a new data type specifies data and operations on the data 44

classes and objects data type is a set of values and a set of operations defined on those values a class is a data type (the cookie cutter) specifies what data can be stored instance attributes defines operations on that data instance methods 45

classes and objects data type is a set of values and a set of operations defined on those values a class is a data type (the cookie cutter) specifies what data can be stored instance attributes defines operations on that data instance methods can have its own data (cookie cutter model number, colour, etc) class attributes / static attributes / class fields 45

classes and objects data type is a set of values and a set of operations defined on those values a class is a data type (the cookie cutter) specifies what data can be stored instance attributes defines operations on that data instance methods can have its own data (cookie cutter model number, colour, etc) class attributes / static attributes / class fields can have its own functionality (bottle opener?) class methods / static methods (functions) 45

classes and objects data type is a set of values and a set of operations defined on those values a class is a data type (the cookie cutter) specifies what data can be stored instance attributes defines operations on that data instance methods can have its own data (cookie cutter model number, colour, etc) class attributes / static attributes / class fields can have its own functionality (bottle opener?) class methods / static methods (functions) an object is an instantiation of a class (the cookie) holds data (the state of the object) instance attributes has operations built-in to it (the bahaviour of the object) instance methods 45

anatomy of a class (part I) public class MyClass{ /* instance attributes */ public int a; private String s;... /* constructors */ public MyClass(){... } public MyClass(int x){... }... } /* instance methods */ public int addone(){...}...... /* class methods */ public static void main(string[] args){...} 46

anatomy of a class (part I) public class MyClass{ /* instance attributes */ this will define the STATE public int a; (set of values) private String s;... /* constructors */ initialization code public MyClass(){... } public MyClass(int x){... }... } /* instance methods */ this defines the BEHAVIOUR public int addone(){...} (operations on the values)...... /* class methods */ class methods public static void main(string[] args){...} 46

basic class public class Student{ /* instance attributes */ public String name; public int id; } 47

basic class public class Student{ /* instance attributes */ public String name; public int id; } simple aggregation of data array was good for collecting together data of the same type (doesn t work for different data though) this is essentially a record in Pascal or a struct in C 47

basic class public class Student{ /* instance attributes */ public String name; public int id; } declare variable of type Student like any other variable Student s; instantiate the actual object with new and constructor s = new Student(); access attributes with dot operator s.name = "fig"; 48

basic class Student s = new Student(); Student() is a constructor for Student class Java will provide a default constructor if and only if you do not provide any constructors default constructor has no input parameters you can define as many constructors as you see fit Java allows method overloading Java methods uniquely specified by name and input arguments you can have many methods with the same name 49

basic class public class Student{ public String name; public int id; } public Student(){ name = "none"; id = -1; } 50

basic class public class Student{ public String name; public int id; } public Student(){ name = "none"; id = -1; } constructor has no return value (this is different than returning nothing; void) 50

basic class public class Student{ public String name; public int id; } public Student(){ name = "none"; id = -1; } constructor has no return value (this is different than returning nothing; void) constructor name is identical to class name 50

basic class public class Student{ public String name; public int id; } public Student(){ name = "none"; id = -1; } constructor has no return value (this is different than returning nothing; void) constructor name is identical to class name executes initialization/start-up code when we create an object 50

basic class public class Student{ public String name; public int id; } public Student(){ name = "none"; id = -1; } constructor has no return value (this is different than returning nothing; void) constructor name is identical to class name executes initialization/start-up code when we create an object constructors are not methods 50

basic class public class Student{ public String name; public int id; } public Student(String name, int id){ name = name; id = id; } 51

basic class public class Student{ public String name; public int id; } public Student(String name, int id){ this.name = name; this.id = id; } Java keyword this used in constructors and instance methods a reference to the current object has other uses we ll discuss later this is needed here because attributes name and id are not in scope (the input parameters name and id are in scope) 51

basic class public class Student{ public String name; public int id; } public Student(String nameinit, int idinit){ name = nameinit; id = idinit; } this is not needed here 52

basic class public class Student{ public String name; public int id; } public Student(String nameinit, int idinit){ this.name = nameinit; this.id = idinit; } this is not needed here you can still use it though! I will often include it in constructors for this course 52

basic class public class Student{ public String name; public int id; public Student(String nameinit, int idinit){ this.name = nameinit; this.id = idinit; } } public Student(String nameinit){ this.name = nameinit; this.id = -1; } Java allows method and constructor overloading can have as many constructors as is useful 53

basic class public class Student{ public String name; public int id; } class does not need to have a constructor specified 54

basic class public class Student{ public String name; public int id; } public Student(){ } class does not need to have a constructor specified Java automatically provides a zero argument default constructor if none are specified it does nothing 54

basic class public class Student{ public String name; public int id; } public Student(){ } class does not need to have a constructor specified Java automatically provides a zero argument default constructor if none are specified it does nothing Java does this only if NO constructors are specified 54

let s take a break... for 5 minutes 55

encapsulation (again) encapsulation can also refer to a language mechanism for restricting access to some of the object s components. [wiki] often called information hiding related to idea of separation of concerns actual code and how you use the code are independent access to data is restricted through getter and setter methods (if accessible) (this is the interface in which you access data) some data is completely hidden within the object why would we want to do this? 56

encapsulation (again) encapsulation can also refer to a language mechanism for restricting access to some of the object s components. [wiki] often called information hiding related to idea of separation of concerns actual code and how you use the code are independent access to data is restricted through getter and setter methods (if accessible) (this is the interface in which you access data) some data is completely hidden within the object why would we want to do this? what happens if you change how you store your data? if someone has access to a variable, will they modify it? 56

encapsulation public class Student{ public String name; public int id; } public Student(String name, int id) {this.name = name; this.id = id; } 57

encapsulation public class Student{ private String name; private int id; } public Student(String name, int id) {this.name = name; this.id = id; } 58

encapsulation public class Student{ private String name; private int id; public String getname() {return this.name;} public void setname(string newname) // setter for name {this.name = newname;} } public Student(String name, int id) {this.name = name; this.id = id; } 59

encapsulation public class Student{ private String name; private int id; public String getname() {return this.name;} public String setname(string newname) // setter for name {this.name = newname; return this.name;} } public Student(String name, int id) {this.name = name; this.id = id; } 60

encapsulation public class Student{ private String name; private int id; public String getname() {return this.name;} public Student setname(string newname) // setter for name {this.name = newname; return this;} } public Student(String name, int id) {this.name = name; this.id = id; } 61

encapsulation public class Student{ private String name; private int id; public String getname() {return this.name;} public boolean setname(string newname, Cred cred){ // setter for name if( isvalidcredential(cred)){ this.name = newname; return true; }else{ return false; } } } public Student(String name, int id) {this.name = name; this.id = id; } 62

Java s Object class public class Object{ /* no attributes */ /* single constructor */ public Object(){} } /* 11 methods */ public String tostring(){...} public int hashcode(){...} public boolean equals(object obj){...}... java.lang.object this is Java s basic non-primitive type 63

Java s Object class public class Student { /* attributes */ public String name; public int id; } 64

Java s Object class public class Student extends Object{ /* attributes */ public String name; public int id; } implicit inheritance to Object if none given Java keyword extends used for inheritance 64

Java s Object class public class Student extends Object{ /* attributes */ public String name; public int id; } implicit inheritance to Object if none given Java keyword extends used for inheritance when we inherit from a class we get all public attributes from the parent class we get all public methods from the parent class we get none of the constructors 64

Java s Object class public class Student extends Object{ /* attributes */ public String name; public int id; } implicit inheritance to Object if none given Java keyword extends used for inheritance when we inherit from a class we get all public attributes from the parent class we get all public methods from the parent class we get none of the constructors we say that Student is an Object this is the is-a relationship 64

Java s Object class public class Student extends Object{ /* attributes */ public String name; public int id; } implicit inheritance to Object if none given Java keyword extends used for inheritance when we inherit from a class we get all public attributes from the parent class we get all public methods from the parent class we get none of the constructors we say that Student is an Object this is the is-a relationship we say that Student has a String this is the has-a relationship this is class composition (not inheritance) 64

inheritance public class Student extends Object{ /* attributes */ public String name; public int id; } a class can only have one parent class every class, except Object, has exactly one parent class we get a hierarchy of classes a family tree of classes 65

inheritance public class Student extends Object{ /* attributes */ public String name; public int id; } 66

inheritance public class Student extends Object{ /* attributes */ public String name; public int id; } we say that Student is a child class of Object Student is a subclass of Object Student is a derived class of Object Student is a descendent of Object 66

inheritance public class Student extends Object{ /* attributes */ public String name; public int id; } we say that Student is a child class of Object Student is a subclass of Object Student is a derived class of Object Student is a descendent of Object we say that Object is a parent class of Student Object is a super class of Student Object is a ancestor of Student 66

inheritance public class Student extends Object{ /* attributes */ public String name; public int id; } what do we get from Object? 67

inheritance - method overriding public class Student extends Object{ /* attributes */ public String name; public int id; public String tostring(){...} } 68

inheritance - method overriding public class Student extends Object{ /* attributes */ public String name; public int id; public String tostring(){...} } method overriding allows us to redefine a parent s (or grandparent s) method definition 68

inheritance - method overriding public class Student extends Object{ /* attributes */ public String name; public int id; public String tostring(){...} } method overriding allows us to redefine a parent s (or grandparent s) method definition which method is executed? 68

inheritance - method overriding public class Student extends Object{ /* attributes */ public String name; public int id; public String tostring(){...} } method overriding allows us to redefine a parent s (or grandparent s) method definition which method is executed? Java first looks in current class if method is not defined, look at parent class if method is not defined, look at parent class... get method from Object 68

inheritance - method overriding let s see some examples... 69