SlideShare ist ein Scribd-Unternehmen logo
1 von 50
Object-Oriented Programming
Concepts
Chapter 2
Software Development: A 5-Step Process
1) Analysis
– English description of what the
system models to meet user requirement / specification
2) Designing the system
– divide & conquer: system is composed of smaller subsystems which in turn may be composed of even
smaller subsystems (diagrams often helpful)
3) Implementing the design (in a particular programming language)
– if design is good, most of the hard work should be done
4) Testing and Debugging
– testing: submitting input data or sample user interactions and seeing if program reacts properly
– debugging: process of removing program bugs (errors)
5) Maintenance
– in a successful piece of software, keeping a program working and current is often said to be 80% of the
effort
Good Program:
– solves original problem
– well-structured, extensible, maintainable, efficient
Object-Oriented Programming
• OOP: Now the dominant way to program, yet it is over 40
years old! (Simula '67 and Smalltalk '72 were the first OOPLs)
– Dr. Alan Kay received ACM’s Turing Award, the
“Nobel Prize of Computing,” in 2003 for Smalltalk,
the first complete dynamic OOPL
• It was slow to catch on, but since the mid-90’s everybody’s
been doing it!
• OOP emphasizes objects, which often reflect real-life objects
– have both properties and capabilities
– i.e., they can perform tasks: “they know how to...”
• Look around you... name that object!
OOP as Modeling
• In OOP, model program as collection of cooperating objects
– program behavior is determined by group interactions
– group interactions are determined by individual objects
• In OOP, objects are considered anthropomorphic
– each is “smart” in its specialty
– e.g., bed can make itself, door can open itself, menu can let
selections be picked
– but, each must be told when to perform actions by another object
— so objects must cooperate to accomplish task
• Each object represents an abstraction
– a “black box”: hides details you do not care about
– allows you as the programmer to control program’s complexity —
only think about salient features
• So, write programs by modeling problem as set of collaborating
components
– you determine what the building blocks are
– put them together so they cooperate properly
– like building a circuit with discrete/integrated components, some of
which are pre-defined, some of which you design!
Example: Tetris
• What are the game’s objects?
• What do those objects know how to do?
• What properties do they have?
Example: Tetris (cont.)
• What are the game’s objects?
– piece, board
• Capabilities: What do those objects know how to do?
– piece:
• be created
• fall
• rotate
• stop at collision
– board:
• be created
• remove rows
• check for end of game
• Properties: What attributes and components do they have?
– piece:
• orientation
• position
• shape
• color
– board:
• size
• rows
DATA ABSTRACTION AND
ABSTRACT DATA TYPES
Why do we need data abstraction?
Data abstraction (by defining ADTs) is very important to represent our
model of the real world problem at hand.
Complex realities are made more manageable by
abstract models.
An Example Data Abstraction
Note the difference between data and procedural abstraction.
A Complex Number
Data Abstraction (STATE) vs. Procedural Abstraction (BEHAVIOR)
Data
Real Part
Imaginary Part
? Angle
? Magnitude
Procedures
Add
Multiply
GetMagnitude
GetAngle
?
?
Abstract Data Types (ADTs)
• Object-oriented programming embodies both
procedural abstraction and data abstraction.
– Procedural Abstraction:- Naming a segment of
code so that it can be executed by giving its name.
E.g. calculateAverage, drawCircle, getUserName, sqrt
– Data Abstraction:- A data abstraction consists of
the following three parts:
• A set S of objects, whose representation structure is undefined.
• A set P of operations defined on elements of S.
• A set R of rules that define the operations and relationships
between the elements of the set.
E.g. an integer (abstracted in C/C++/Java as int)
Abstract Data Types (ADTs)
• An abstract data type is a set of data abstractions,
each with its own elements, operations and rules,
where one of the data abstractions within the ADT is
specified as the principal data abstraction.
Examples:
An array (of integers)
A string (of characters)
A queue(of people)
A list(of students),
A stack(of dishes),…
Commonly Used ADTs
• Some common ADTs, which have proved useful
in a great variety of applications, include:
Note:
1. You can find commonly used ADTs implemented in PLs like C++, C# and Java
C++ (the Standard Template Library)
C# (.NET’s System.Generics.Collections)
Java (java.util.* - the Java Collection library) – more on this later
2. Plus you can implement your own (Data Structures is a separate course, but you’d
be able to create and/or use basic ADTs)
– A QUICK DEMO
Implementing ADTs
• An ADT is often implemented as class
16
A Look at Java ADTs
Lists and Iterators
Scope and Packages
17
Content
• Lists
– ArrayList
– LinkedList
• Iterators
• Access
• Package
• Scope
Built-in ADTs, very useful.
18
Arrays Review
• Arrays are a simple data structure
• Arrays store a row of values of the same type
– Primitive types (int, double, etc.)
// array that can hold 10 chars
char[] letters = new char[10];
– Objects (Students, Dates etc.)
// array that can hold 3 LightSwitches
LightSwitch[] switches = new LightSwitch[3];
19
Arrays Review
• Access each value through an index:
int[] intArray = new int[20];
intArray[0] = 4 ; intArray[1] = 75;
• Array indices start at 0, not 1
– first element of intArray is intArray[0]
– last element of intArray is intArray[19]
• Important: Array lengths cannot be changed
once they are declared!
20
ArrayList
• ArrayList stores its elements internally as
an array. However, its size can be modified
once declared.
• get method is fast – just retrieves the element
at the specified index
• add method is slow – may have to create a
larger array and copy over all the elements.
21
Linked List Data Structure
• A linked list is like a freight train: each link stores
an item and is connected to the next link
• The list holds a reference to the first (and maybe
the last) element
Linked List Link 1 Link 2 Link n
Item 1 Item 2 Item n
. . .
22
LinkedList
• LinkedList stores its elements internally in
a linked list data structure.
• add method is fast – just appends a new link
to the end of the list
• get method is slow – has to walk down the
list retrieve the element at the specified index
23
iterator method
• Both ArrayList and LinkedList
have a method named iterator
• Returns an object of type Iterator
• We use the Iterator to iterate over the
elements of the list.
24
Iterators
• We use Iterators to iterate over the
elements of lists
• hasNext method returns true when
there are more elements to iterate over
• next method returns the next element
in the iteration
25
Casting
• Because the next method returns type
Object, you must cast the return value to
the actual type of the value.
• "Casting" means "promising" the compiler
that the object will be of a particular type
• This allows you to use methods of the actual
type without the compiler complaining
26
GradeBook Iteration
class GradeBook {
private ArrayList grades;
void printGrades() {
Iterator gradeIter = grades.iterator();
while(gradeIter.hasNext()) {
Double g =(Double)gradeIter.next();
System.out.println(g.doubleValue());
}
}
}
27
Access & Organization
• Let’s say you have 100’s of files on your PC.
What kind of problems do you encounter?
– can’t find particular files
– duplicate or similar file names
– hard to keep personal files private
• Solution: Sort and organize your files into
subdirectories
28
Packages
• Organize your classes into sets or units
• Reduce problems with name conflicts
• Identify your classes in a set with specific
functionality
How to specify the package for a class:
package <package name>;
29
Using Packages
• A class can always access other classes in its
own package
• A class can always access public classes in
other packages
Q: What happens if we don’t specify a class
as public or private?
A: the default level of access is package
30
Levels of Access Control
Visibility private package
(default)
public
From the same
class
yes yes yes
From any class
in same package
no yes yes
From any class
outside the
package
no no yes
31
Import Classes and Packages
• Specify the class you want to import:
import java.util.Date;
• You can import multiple classes:
import java.util.ArrayList;
• You can also import whole packages:
import java.util.*;
• Default imported package:
import java.lang.*;
32
Package Example: Person.java
package examples;
class Person {
String name;
// add a field to store a birthday
// write a method to set the birthday
// write a method to get the birthday
}
33
Using java.util.Date
package examples;
class Person {
String name;
java.util.Date birthday;
void setBirthday(java.util.Date d) {
birthday = d;
}
java.util.Date getBirthday() {
return birthday;
}
}
34
Importing java.util.Date
package examples;
import java.util.Date;
class Person {
String name;
Date birthday;
void setBirthday(Date d) {
birthday = d;
}
Date getBirthday() {
return birthday;
}
}
35
Importing java.util.ArrayList
package examples;
import java.util.Date;
import java.util.ArrayList;
class Person {
String name;
Date birthday;
ArrayList friends;
void setBirthday(Date d) {
birthday = d;
}
// . . .
}
36
Importing java.util.*
package examples;
import java.util.*;
class Person {
String name;
Date birthday;
ArrayList friends;
void setBirthday(Date d) {
birthday = d;
}
// . . .
}
37
Packages Quiz 1
package example1;
public class A {
public int a = 5;
}
package example1;
public class B {
int b = 5;
}
package example1;
public class C {
private int c = 5;
}
package example1;
public class quiz{
void main() {
A ant = new A();
B bug = new B();
C cat = new C();
// Which are correct?
int testa = ant.a;
int testb = bug.b;
int testc = cat.c;
}
}
38
Package Quiz 2
package example2;
import example1.*;
public class quiz{
void main() {
A ant = new A();
B bug = new B();
C cat = new C();
// Which are correct?
int testa = ant.a;
int testb = bug.b;
int testc = cat.c;
}
}
package example1;
public class A {
public int a = 5;
}
package example1;
public class B {
int b = 5;
}
package example1;
public class C {
private int c = 5;
}
39
SCOPE
40
Scope of a Variable
• Definition: the block (section) of code for
which your variable (identifier) exists
• The scope is set to the block in which you
defined your variable
• This is the block of code where you can use
the variable
41
Scope Quiz 1
class TestScope {
int x = 0;
void f() {
int y = 20;
x = 10;
}
void print() {
System.out.println(x);
f();
System.out.println(x);
System.out.println(y);
}
}
What is the output of
print()?
This file won't
compile, so print will
never execute
42
Method Scope
class TestScope {
int x = 0;
void f() {
int y = 20;
x = 10;
}
void print() {
System.out.println(x);
f();
System.out.println(x);
System.out.println(y); // ERROR
}
}
• x is defined for the
whole class block.
• y is defined inside the
method f().
43
Scope Quiz 2
class TestScope {
int x = 0;
void f() {
int y = 20;
x = 10;
}
void print() {
int y = 0;
System.out.println(x);
f();
System.out.println(x);
System.out.println(y);
}
}`
Does this fix the
problem?
What is the output
of print()?
0
10
0
44
Scope Quiz 3
class TestScope {
int x = 0;
int y = 0;
void f() {
int y;
y = 20;
x = 10;
}
void print() {
System.out.println(x);
f();
System.out.println(x);
System.out.println(y);
}
}
Now, we declare a
new field, y.
What is the output of
print()?
0
10
0
45
Scope Quiz 4
class TestScope {
int x = 0;
int y = 0;
void f() {
y = 20;
x = 10;
}
void print() {
System.out.println(x);
f();
System.out.println(x);
System.out.println(y);
}
}
Now, we change the
method f().
What is the output of
print()?
0
10
20
46
Scope Quiz 5
package examples;
class Operations{
int square(int a) {
a = a * a;
return a;
}
void print() {
int a = 5;
System.out.println(square(a));
System.out.println(a);
}
}
• What is the output of
print()?
25 <- square(a)
5 <- a
47
Scope Quiz 6
package examples;
class Operations{
int a = 5;
int square(int a) {
a = a * a;
return a;
}
void print() {
System.out.println(square(a));
System.out.println(a);
}
}
• What is the output of
print()?
25 <- square(a)
5 <- a
48
Scope Quiz 7
package examples;
class Operations{
int a = 5;
int square(int a) {
this.a = a*a;
return a;
}
void print() {
System.out.println(square(a));
System.out.println(a);
}
}
• What is the output of
print()?
5 <- square(a)
25 <- a
49
Loop Scope
void adding() {
for (int j = 0; j<5; j++) {
int sum += j;
}
System.out.println(sum);
}
• What’s wrong with the above segment of code?
ERROR: sum is only defined inside the for loop
50
Loop Scope Fixed
void adding() {
int sum = 0;
for (int j = 0; j<5; j++) {
sum += j;
}
System.out.println(sum);
}
• sum is now defined for the whole block of
code for the adding method

Weitere ähnliche Inhalte

Ähnlich wie 02._Object-Oriented_Programming_Concepts.ppt

Presentation 4th
Presentation 4thPresentation 4th
Presentation 4th
Connex
 
Ccourse 140618093931-phpapp02
Ccourse 140618093931-phpapp02Ccourse 140618093931-phpapp02
Ccourse 140618093931-phpapp02
Getachew Ganfur
 

Ähnlich wie 02._Object-Oriented_Programming_Concepts.ppt (20)

07slide.ppt
07slide.ppt07slide.ppt
07slide.ppt
 
Intro_2.ppt
Intro_2.pptIntro_2.ppt
Intro_2.ppt
 
Intro.ppt
Intro.pptIntro.ppt
Intro.ppt
 
Intro.ppt
Intro.pptIntro.ppt
Intro.ppt
 
class as the basis.pptx
class as the basis.pptxclass as the basis.pptx
class as the basis.pptx
 
Java OOP Programming language (Part 4) - Collection
Java OOP Programming language (Part 4) - CollectionJava OOP Programming language (Part 4) - Collection
Java OOP Programming language (Part 4) - Collection
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
C# classes objects
C#  classes objectsC#  classes objects
C# classes objects
 
STRINGS IN JAVA
STRINGS IN JAVASTRINGS IN JAVA
STRINGS IN JAVA
 
00-review.ppt
00-review.ppt00-review.ppt
00-review.ppt
 
Chap01
Chap01Chap01
Chap01
 
Lecture 4 - Object Interaction and Collections
Lecture 4 - Object Interaction and CollectionsLecture 4 - Object Interaction and Collections
Lecture 4 - Object Interaction and Collections
 
Presentation 4th
Presentation 4thPresentation 4th
Presentation 4th
 
Ccourse 140618093931-phpapp02
Ccourse 140618093931-phpapp02Ccourse 140618093931-phpapp02
Ccourse 140618093931-phpapp02
 
C++ Programming Course
C++ Programming CourseC++ Programming Course
C++ Programming Course
 
Module 3,4.pptx
Module 3,4.pptxModule 3,4.pptx
Module 3,4.pptx
 
C++ training
C++ training C++ training
C++ training
 
Data Structure and Algorithms
Data Structure and AlgorithmsData Structure and Algorithms
Data Structure and Algorithms
 
Mathemetics module
Mathemetics moduleMathemetics module
Mathemetics module
 
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
 

Mehr von Yonas D. Ebren (11)

Group presentation.pptx
Group presentation.pptxGroup presentation.pptx
Group presentation.pptx
 
P15_Analog_Filters_P1.pdf
P15_Analog_Filters_P1.pdfP15_Analog_Filters_P1.pdf
P15_Analog_Filters_P1.pdf
 
P4_Predictive_Modeling_Speech.pdf
P4_Predictive_Modeling_Speech.pdfP4_Predictive_Modeling_Speech.pdf
P4_Predictive_Modeling_Speech.pdf
 
Group Task Presentation.pptx
Group Task Presentation.pptxGroup Task Presentation.pptx
Group Task Presentation.pptx
 
bible study.pptx
bible study.pptxbible study.pptx
bible study.pptx
 
Algorithms of FFT.pptx
Algorithms of FFT.pptxAlgorithms of FFT.pptx
Algorithms of FFT.pptx
 
Applications.pptx
Applications.pptxApplications.pptx
Applications.pptx
 
Presentation4.pptx
Presentation4.pptxPresentation4.pptx
Presentation4.pptx
 
Presentation3.pptx
Presentation3.pptxPresentation3.pptx
Presentation3.pptx
 
Presentation2.pptx
Presentation2.pptxPresentation2.pptx
Presentation2.pptx
 
Presentation1.pptx
Presentation1.pptxPresentation1.pptx
Presentation1.pptx
 

Kürzlich hochgeladen

+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
anilsa9823
 

Kürzlich hochgeladen (20)

W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 

02._Object-Oriented_Programming_Concepts.ppt

  • 2. Software Development: A 5-Step Process 1) Analysis – English description of what the system models to meet user requirement / specification 2) Designing the system – divide & conquer: system is composed of smaller subsystems which in turn may be composed of even smaller subsystems (diagrams often helpful) 3) Implementing the design (in a particular programming language) – if design is good, most of the hard work should be done 4) Testing and Debugging – testing: submitting input data or sample user interactions and seeing if program reacts properly – debugging: process of removing program bugs (errors) 5) Maintenance – in a successful piece of software, keeping a program working and current is often said to be 80% of the effort Good Program: – solves original problem – well-structured, extensible, maintainable, efficient
  • 3. Object-Oriented Programming • OOP: Now the dominant way to program, yet it is over 40 years old! (Simula '67 and Smalltalk '72 were the first OOPLs) – Dr. Alan Kay received ACM’s Turing Award, the “Nobel Prize of Computing,” in 2003 for Smalltalk, the first complete dynamic OOPL • It was slow to catch on, but since the mid-90’s everybody’s been doing it! • OOP emphasizes objects, which often reflect real-life objects – have both properties and capabilities – i.e., they can perform tasks: “they know how to...” • Look around you... name that object!
  • 4. OOP as Modeling • In OOP, model program as collection of cooperating objects – program behavior is determined by group interactions – group interactions are determined by individual objects • In OOP, objects are considered anthropomorphic – each is “smart” in its specialty – e.g., bed can make itself, door can open itself, menu can let selections be picked – but, each must be told when to perform actions by another object — so objects must cooperate to accomplish task • Each object represents an abstraction – a “black box”: hides details you do not care about – allows you as the programmer to control program’s complexity — only think about salient features • So, write programs by modeling problem as set of collaborating components – you determine what the building blocks are – put them together so they cooperate properly – like building a circuit with discrete/integrated components, some of which are pre-defined, some of which you design!
  • 5. Example: Tetris • What are the game’s objects? • What do those objects know how to do? • What properties do they have?
  • 6. Example: Tetris (cont.) • What are the game’s objects? – piece, board • Capabilities: What do those objects know how to do? – piece: • be created • fall • rotate • stop at collision – board: • be created • remove rows • check for end of game • Properties: What attributes and components do they have? – piece: • orientation • position • shape • color – board: • size • rows
  • 8. Why do we need data abstraction? Data abstraction (by defining ADTs) is very important to represent our model of the real world problem at hand.
  • 9. Complex realities are made more manageable by abstract models.
  • 10. An Example Data Abstraction Note the difference between data and procedural abstraction.
  • 11. A Complex Number Data Abstraction (STATE) vs. Procedural Abstraction (BEHAVIOR) Data Real Part Imaginary Part ? Angle ? Magnitude Procedures Add Multiply GetMagnitude GetAngle ? ?
  • 12. Abstract Data Types (ADTs) • Object-oriented programming embodies both procedural abstraction and data abstraction. – Procedural Abstraction:- Naming a segment of code so that it can be executed by giving its name. E.g. calculateAverage, drawCircle, getUserName, sqrt – Data Abstraction:- A data abstraction consists of the following three parts: • A set S of objects, whose representation structure is undefined. • A set P of operations defined on elements of S. • A set R of rules that define the operations and relationships between the elements of the set. E.g. an integer (abstracted in C/C++/Java as int)
  • 13. Abstract Data Types (ADTs) • An abstract data type is a set of data abstractions, each with its own elements, operations and rules, where one of the data abstractions within the ADT is specified as the principal data abstraction. Examples: An array (of integers) A string (of characters) A queue(of people) A list(of students), A stack(of dishes),…
  • 14. Commonly Used ADTs • Some common ADTs, which have proved useful in a great variety of applications, include: Note: 1. You can find commonly used ADTs implemented in PLs like C++, C# and Java C++ (the Standard Template Library) C# (.NET’s System.Generics.Collections) Java (java.util.* - the Java Collection library) – more on this later 2. Plus you can implement your own (Data Structures is a separate course, but you’d be able to create and/or use basic ADTs) – A QUICK DEMO
  • 15. Implementing ADTs • An ADT is often implemented as class
  • 16. 16 A Look at Java ADTs Lists and Iterators Scope and Packages
  • 17. 17 Content • Lists – ArrayList – LinkedList • Iterators • Access • Package • Scope Built-in ADTs, very useful.
  • 18. 18 Arrays Review • Arrays are a simple data structure • Arrays store a row of values of the same type – Primitive types (int, double, etc.) // array that can hold 10 chars char[] letters = new char[10]; – Objects (Students, Dates etc.) // array that can hold 3 LightSwitches LightSwitch[] switches = new LightSwitch[3];
  • 19. 19 Arrays Review • Access each value through an index: int[] intArray = new int[20]; intArray[0] = 4 ; intArray[1] = 75; • Array indices start at 0, not 1 – first element of intArray is intArray[0] – last element of intArray is intArray[19] • Important: Array lengths cannot be changed once they are declared!
  • 20. 20 ArrayList • ArrayList stores its elements internally as an array. However, its size can be modified once declared. • get method is fast – just retrieves the element at the specified index • add method is slow – may have to create a larger array and copy over all the elements.
  • 21. 21 Linked List Data Structure • A linked list is like a freight train: each link stores an item and is connected to the next link • The list holds a reference to the first (and maybe the last) element Linked List Link 1 Link 2 Link n Item 1 Item 2 Item n . . .
  • 22. 22 LinkedList • LinkedList stores its elements internally in a linked list data structure. • add method is fast – just appends a new link to the end of the list • get method is slow – has to walk down the list retrieve the element at the specified index
  • 23. 23 iterator method • Both ArrayList and LinkedList have a method named iterator • Returns an object of type Iterator • We use the Iterator to iterate over the elements of the list.
  • 24. 24 Iterators • We use Iterators to iterate over the elements of lists • hasNext method returns true when there are more elements to iterate over • next method returns the next element in the iteration
  • 25. 25 Casting • Because the next method returns type Object, you must cast the return value to the actual type of the value. • "Casting" means "promising" the compiler that the object will be of a particular type • This allows you to use methods of the actual type without the compiler complaining
  • 26. 26 GradeBook Iteration class GradeBook { private ArrayList grades; void printGrades() { Iterator gradeIter = grades.iterator(); while(gradeIter.hasNext()) { Double g =(Double)gradeIter.next(); System.out.println(g.doubleValue()); } } }
  • 27. 27 Access & Organization • Let’s say you have 100’s of files on your PC. What kind of problems do you encounter? – can’t find particular files – duplicate or similar file names – hard to keep personal files private • Solution: Sort and organize your files into subdirectories
  • 28. 28 Packages • Organize your classes into sets or units • Reduce problems with name conflicts • Identify your classes in a set with specific functionality How to specify the package for a class: package <package name>;
  • 29. 29 Using Packages • A class can always access other classes in its own package • A class can always access public classes in other packages Q: What happens if we don’t specify a class as public or private? A: the default level of access is package
  • 30. 30 Levels of Access Control Visibility private package (default) public From the same class yes yes yes From any class in same package no yes yes From any class outside the package no no yes
  • 31. 31 Import Classes and Packages • Specify the class you want to import: import java.util.Date; • You can import multiple classes: import java.util.ArrayList; • You can also import whole packages: import java.util.*; • Default imported package: import java.lang.*;
  • 32. 32 Package Example: Person.java package examples; class Person { String name; // add a field to store a birthday // write a method to set the birthday // write a method to get the birthday }
  • 33. 33 Using java.util.Date package examples; class Person { String name; java.util.Date birthday; void setBirthday(java.util.Date d) { birthday = d; } java.util.Date getBirthday() { return birthday; } }
  • 34. 34 Importing java.util.Date package examples; import java.util.Date; class Person { String name; Date birthday; void setBirthday(Date d) { birthday = d; } Date getBirthday() { return birthday; } }
  • 35. 35 Importing java.util.ArrayList package examples; import java.util.Date; import java.util.ArrayList; class Person { String name; Date birthday; ArrayList friends; void setBirthday(Date d) { birthday = d; } // . . . }
  • 36. 36 Importing java.util.* package examples; import java.util.*; class Person { String name; Date birthday; ArrayList friends; void setBirthday(Date d) { birthday = d; } // . . . }
  • 37. 37 Packages Quiz 1 package example1; public class A { public int a = 5; } package example1; public class B { int b = 5; } package example1; public class C { private int c = 5; } package example1; public class quiz{ void main() { A ant = new A(); B bug = new B(); C cat = new C(); // Which are correct? int testa = ant.a; int testb = bug.b; int testc = cat.c; } }
  • 38. 38 Package Quiz 2 package example2; import example1.*; public class quiz{ void main() { A ant = new A(); B bug = new B(); C cat = new C(); // Which are correct? int testa = ant.a; int testb = bug.b; int testc = cat.c; } } package example1; public class A { public int a = 5; } package example1; public class B { int b = 5; } package example1; public class C { private int c = 5; }
  • 40. 40 Scope of a Variable • Definition: the block (section) of code for which your variable (identifier) exists • The scope is set to the block in which you defined your variable • This is the block of code where you can use the variable
  • 41. 41 Scope Quiz 1 class TestScope { int x = 0; void f() { int y = 20; x = 10; } void print() { System.out.println(x); f(); System.out.println(x); System.out.println(y); } } What is the output of print()? This file won't compile, so print will never execute
  • 42. 42 Method Scope class TestScope { int x = 0; void f() { int y = 20; x = 10; } void print() { System.out.println(x); f(); System.out.println(x); System.out.println(y); // ERROR } } • x is defined for the whole class block. • y is defined inside the method f().
  • 43. 43 Scope Quiz 2 class TestScope { int x = 0; void f() { int y = 20; x = 10; } void print() { int y = 0; System.out.println(x); f(); System.out.println(x); System.out.println(y); } }` Does this fix the problem? What is the output of print()? 0 10 0
  • 44. 44 Scope Quiz 3 class TestScope { int x = 0; int y = 0; void f() { int y; y = 20; x = 10; } void print() { System.out.println(x); f(); System.out.println(x); System.out.println(y); } } Now, we declare a new field, y. What is the output of print()? 0 10 0
  • 45. 45 Scope Quiz 4 class TestScope { int x = 0; int y = 0; void f() { y = 20; x = 10; } void print() { System.out.println(x); f(); System.out.println(x); System.out.println(y); } } Now, we change the method f(). What is the output of print()? 0 10 20
  • 46. 46 Scope Quiz 5 package examples; class Operations{ int square(int a) { a = a * a; return a; } void print() { int a = 5; System.out.println(square(a)); System.out.println(a); } } • What is the output of print()? 25 <- square(a) 5 <- a
  • 47. 47 Scope Quiz 6 package examples; class Operations{ int a = 5; int square(int a) { a = a * a; return a; } void print() { System.out.println(square(a)); System.out.println(a); } } • What is the output of print()? 25 <- square(a) 5 <- a
  • 48. 48 Scope Quiz 7 package examples; class Operations{ int a = 5; int square(int a) { this.a = a*a; return a; } void print() { System.out.println(square(a)); System.out.println(a); } } • What is the output of print()? 5 <- square(a) 25 <- a
  • 49. 49 Loop Scope void adding() { for (int j = 0; j<5; j++) { int sum += j; } System.out.println(sum); } • What’s wrong with the above segment of code? ERROR: sum is only defined inside the for loop
  • 50. 50 Loop Scope Fixed void adding() { int sum = 0; for (int j = 0; j<5; j++) { sum += j; } System.out.println(sum); } • sum is now defined for the whole block of code for the adding method

Hinweis der Redaktion

  1. Graphs, arrays, …