SlideShare a Scribd company logo
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

More Related Content

PPTX
Object Oriented Programming
PDF
Java chapter 3
PPTX
DS 2024 Lecturde dcdcdcdcdcdcd3 & 4.pptx
PPT
Ooad ch 2
DOCX
Unit1 jaava
PPTX
Birasa 1
PPTX
JAVA PROGRAMMING
PPTX
JAVA PROGRAMMINGD
Object Oriented Programming
Java chapter 3
DS 2024 Lecturde dcdcdcdcdcdcd3 & 4.pptx
Ooad ch 2
Unit1 jaava
Birasa 1
JAVA PROGRAMMING
JAVA PROGRAMMINGD

Similar to 02._Object-Oriented_Programming_Concepts.ppt (20)

PPT
Oops Concept Java
PDF
Cs2305 programming paradigms lecturer notes
PPTX
Unit - I Intro. to OOP Concepts and Control Structure -OOP and CG (2024 Patte...
PPTX
DSD Unit 1 Abstract Data Type data structures design notes.pptx
PPT
Oops ppt
PDF
UNIT1- OBJECT ORIENTED PROGRAMMING IN JAVA- AIML IT-SPPU
PPTX
Lecture 01
DOCX
LECTURE NOTES ON Object Oriented Programming Using C++
PPT
OOP Principles
PPTX
Chapter - 1.pptx
PPTX
Std 12 computer chapter 6 object oriented concepts (part 1)
PPTX
UNIT I OOP AND JAVA FUNDAMENTALS CONSTRUCTOR
PPTX
Advanced Topics on Database - Unit-2 AU17
PPTX
chapterOne.pptxFSdgfqdzwwfagxgghvkjljhcxCZZXvcbx
PPTX
OOPJ.pptx
PPT
1-Lec - Introduction vhvv,vbvv,v (2).ppt
PPTX
General oop concept
PPTX
1 intro
PPTX
Introduction to Object oriented Programming basics
PPT
Oop(object oriented programming)
Oops Concept Java
Cs2305 programming paradigms lecturer notes
Unit - I Intro. to OOP Concepts and Control Structure -OOP and CG (2024 Patte...
DSD Unit 1 Abstract Data Type data structures design notes.pptx
Oops ppt
UNIT1- OBJECT ORIENTED PROGRAMMING IN JAVA- AIML IT-SPPU
Lecture 01
LECTURE NOTES ON Object Oriented Programming Using C++
OOP Principles
Chapter - 1.pptx
Std 12 computer chapter 6 object oriented concepts (part 1)
UNIT I OOP AND JAVA FUNDAMENTALS CONSTRUCTOR
Advanced Topics on Database - Unit-2 AU17
chapterOne.pptxFSdgfqdzwwfagxgghvkjljhcxCZZXvcbx
OOPJ.pptx
1-Lec - Introduction vhvv,vbvv,v (2).ppt
General oop concept
1 intro
Introduction to Object oriented Programming basics
Oop(object oriented programming)
Ad

More from Yonas D. Ebren (11)

PPTX
Group presentation.pptx
PDF
P15_Analog_Filters_P1.pdf
PDF
P4_Predictive_Modeling_Speech.pdf
PPTX
Group Task Presentation.pptx
PPTX
bible study.pptx
PPTX
Algorithms of FFT.pptx
PPTX
Applications.pptx
PPTX
Presentation4.pptx
PPTX
Presentation3.pptx
PPTX
Presentation2.pptx
PPTX
Presentation1.pptx
Group presentation.pptx
P15_Analog_Filters_P1.pdf
P4_Predictive_Modeling_Speech.pdf
Group Task Presentation.pptx
bible study.pptx
Algorithms of FFT.pptx
Applications.pptx
Presentation4.pptx
Presentation3.pptx
Presentation2.pptx
Presentation1.pptx
Ad

Recently uploaded (20)

PDF
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
PPTX
history of c programming in notes for students .pptx
PDF
Softaken Excel to vCard Converter Software.pdf
PPTX
Introduction to Artificial Intelligence
PPTX
Essential Infomation Tech presentation.pptx
PDF
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
PPTX
Reimagine Home Health with the Power of Agentic AI​
PDF
How Creative Agencies Leverage Project Management Software.pdf
PDF
Wondershare Filmora 15 Crack With Activation Key [2025
PPTX
Transform Your Business with a Software ERP System
PDF
top salesforce developer skills in 2025.pdf
PPTX
L1 - Introduction to python Backend.pptx
PDF
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
PDF
Understanding Forklifts - TECH EHS Solution
PPTX
Operating system designcfffgfgggggggvggggggggg
PPTX
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
PPTX
ai tools demonstartion for schools and inter college
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PDF
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
PDF
Digital Strategies for Manufacturing Companies
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
history of c programming in notes for students .pptx
Softaken Excel to vCard Converter Software.pdf
Introduction to Artificial Intelligence
Essential Infomation Tech presentation.pptx
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
Reimagine Home Health with the Power of Agentic AI​
How Creative Agencies Leverage Project Management Software.pdf
Wondershare Filmora 15 Crack With Activation Key [2025
Transform Your Business with a Software ERP System
top salesforce developer skills in 2025.pdf
L1 - Introduction to python Backend.pptx
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
Understanding Forklifts - TECH EHS Solution
Operating system designcfffgfgggggggvggggggggg
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
ai tools demonstartion for schools and inter college
Internet Downloader Manager (IDM) Crack 6.42 Build 41
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
Digital Strategies for Manufacturing Companies

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

Editor's Notes

  • #15: Graphs, arrays, …