1.Ders Object_Oriented_Programming
1.Ders Object_Oriented_Programming
Spring 2020
‹#›
Today
Introduction to Java
Java as a Platform
Your First Java Program
Basic Programming Elements
Object Oriented Paradigm
Principles of Object Orientation
Classes and Objects
Sample Object Designs
‹#›
What is Java?
Informal. Brewed coffee.
‹#›
What is Java?
‹#›
Software Development with Java
All source code is first written in plain text files ending with the “.java”
extension.
Those source files are then compiled into “.class” files by the javac compiler.
A “.class” file does not contain code that is native to your processor; it
instead contains bytecodes — the machine language of the Java Virtual
Machine (Java VM).
The java launcher tool then runs your application with an instance of the
Java Virtual Machine, i.e. your code is run by JVM.
http://docs.oracle.com/javase/tutorial/getStarted/intro/definition.html ‹#›
Platform Independence:
Write Once Run Anywhere
Because the Java VM is available on many different operating systems, the
same .class files are capable of running on Microsoft Windows, the Solaris™
Operating System (Solaris OS), Linux, or Mac OS.
http://docs.oracle.com/javase/tutorial/getStarted/intro/definition.html ‹#›
The Java Platform
A platform is the hardware or software environment in which a program runs.
The Java platform has two components:
The Java Virtual Machine: It's the base for the Java platform and is ported onto
various hardware-based platforms
The Java Application Programming Interface (API): It is a large collection of ready-
made software components that provide many useful capabilities.
http://docs.oracle.com/javase/tutorial/getStarted/intro/definition.html ‹#›
Your First Java Program
HelloWorld.java
‹#›
Basic Programming Elements
Variables, Types and Expressions
Flow of Control
Branching
Loops
‹#›
Variables
Variables in a program are used to store data such as numbers
and letters. They can be thought of as containers of a sort.
You should choose variable names that are helpful. Every
variable in a Java program must be declared before it is used for
the first time.
A variable declaration consists of a type name, followed by a list
of variable names separated by commas. The declaration ends
with a semicolon.
Syntax:
data_type variable_name [ = initial_value ];
There are also Class Data Types which we will cover later.
‹#›
Identifiers
The technical term for a name in a programming language, such as
the name of a variable, is an identifier.
An identifier can contain only letters, digits 0 through 9, and the
underscore character “_”.
The first character in an identifier cannot be a digit.
There is no limit to the length of an identifier.
Java is case sensitive (e.g., personName and personname are two
different variables).
Identifier Valid?
outputStream Yes
4you No
my.work No
FirstName Yes
_tmp Yes
public No public is a
reserved word.
‹#›
Java Reserved Words
‹#›
Naming Conventions
Class types begin with an uppercase letter (e.g. String).
‹#›
Assignment Statements
An assignment statement is used to assign a value to a variable.
The "equal sign" is called the assignment operator
Syntax:
variable_name = expression;
amount = 100;
interestRate = 0.12;
answer = ‘Y’;
fullName = firstName + “ “ + lastName;
‹#›
Initializing Variables
A variable that has been declared, but not yet given a value is said to
be uninitialized.
Uninitialized class variables have the value null.
Uninitialized primitive variables may have a default value.
‹#›
Imprecision in Floating Point Numbers
Floating-point numbers often are only approximations since
they are stored with a finite number of bits.
‹#›
Named Constants
Java provides a mechanism that allows you to define a variable,
initialise it, and moreover fix the variable’s value so that it
cannot be changed.
‹#›
Assignment Compatibility
Java is strongly typed.
A value of one type can be assigned to a variable of any type further to the
right (not to the left):
‹#›
Type Conversion (Casting)
Implicit conversion
Explicit conversion
‹#›
Operators and Precedence
Precedence
First: The unary operators: plus (+), minus(-), not (!), increment (++) and
decrement (--)
Second: The binary arithmetic operators: multiplication (*), integer division (/)
and modulus (%)
Third: The binary arithmetic operators: addition (+) and subtraction (-)
‹#›
Operators and Precedence - Example
Figure from “Java - An Introduction to Problem Solving and Programming, Walter Savitch, Pearson, 2012” ‹#›
Arrays
Array is a sequence of values.
Array indices begin at zero.
Defining Arrays
Base_Type[] Array_Name = new Base_Type[Length];
int[] numbers = new int[100]; // or,
int[] numbers;
numbers = new int[100];
Initialising Arrays
double[] reading = {3.3, 15.8, 9.7}; // or,
‹#›
Strings
A value of type String is a
Sequence (Array) of characters treated as a single item
Character positions start with 0
Figure from “Java - An Introduction to Problem Solving and Programming, Walter Savitch, Pearson, 2012” ‹#›
Concatenating Strings
You can connect—or join or paste—two strings together to
obtain a larger string. This operation is called concatenation
and is performed by using the “+” operator.
‹#›
Boolean Type
Java has the logical type boolean
‹#›
Java Comparison Operators
Figure from “Java - An Introduction to Problem Solving and Programming, Walter Savitch, Pearson, 2012” ‹#›
Java Logical Operators
Figure from “Java - An Introduction to Problem Solving and Programming, Walter Savitch, Pearson, 2012” ‹#›
Flow of Control
Flow of control is the order in which a program performs
actions.
‹#›
Basic if Statement
Syntax
if (Expression)
Action
‹#›
if-else Statement
Syntax
if (Expression)
Action1
else
Action2
If Expression is true then execute Action1 otherwise execute
Action2
The actions are either a single statement or a list of statements
within braces
int maximum;
if (value1 < value2) { // is value2 larger?
maximum = value2; // yes: value2 is larger
}
else { // (value1 >= value2)
maximum = value1; // no: value2 is not larger
}
‹#›
if-else Statement
If statements can be nested (also called as multi-way, multi-
branch if statement)
if (a == ‘0’)
System.out.println (“zero”);
else if (a == ‘1’)
System.out.println (“one”);
else if (a == ‘2’)
System.out.println (“two”);
else if (a == ‘3’)
System.out.println (“three”);
else if (a == ‘4’)
System.out.println (“four”);
else
System.out.println (“five+”);
‹#›
Switch Statement
Switch statement can be used instead of multi-way if
statement.
Syntax
switch(controlling_expression) {
case expression1:
action1;
break;
case expression2:
action2;
break;
…
default:
actionN;
}
‹#›
Switch Statement
Switch statements are more readable than nested if statements
switch (a) {
case ‘0’:
System.out.println (“zero”); break;
case ‘1’:
System.out.println (“one”); break;
case ‘2’:
System.out.println (“two”); break;
case ‘3’:
System.out.println (“three”); break;
case ‘4’:
System.out.println (“four”); break;
default:
System.out.println (“five+”); break;
}
‹#›
The Conditional (Ternary) Operator
The ? and : together are called the conditional operator or
ternary operator.
‹#›
for Loops
The for loop is a pretest loop statement. It has the following
form.
‹#›
Varying Control Variable
for ( int i = 1; i <= 100; i++ )
from 1 to 100 in increments of 1
‹#›
For Loop Example
String[] classList = {"Jean", "Claude", "Van",
"Damme"};
‹#›
While Loop
The while loop is a pretest loop statement. It has the following
form.
while (boolean-expression) {
nested-statements
}
‹#›
While Loop Example
int[] numbers = { 1, 5, 3, 4, 2 };
int i=0, key
key == 33;
3; Let’s look for something that does not exist.
if (found)
System.out.println("Key is found in the array");
else
System.out.println("Key is NOT found!");
‹#›
While Loop Example
int[] numbers = { 1, 5, 3, 4, 2 };
int i=0, key
key == 33;
3;
boolean found = false; Make sure that the loop ends somehow.
if (found)
System.out.println("Key is found in the array");
else
System.out.println("Key is NOT found!");
Figure from “Java - An Introduction to Problem Solving and Programming, Walter Savitch, Pearson, 2012” ‹#›
Do-While Loop
The do-while loop is a post-test loop statement. It has the
following form.
do {
nested-statements
} while (boolean-expression);
‹#›
Do-While Example
do {
System.out.println(
"Enter a number between 0 and 100: ");
myNumber = scan.nextInt();
‹#›
Break Statement
The break statement is used in loop (for, while, and do-while)
statements and switch statements to terminate execution of
the statement. A break statement has the following form.
break;
‹#›
Continue Statement
A continue statement
Ends current loop iteration
Begins the next one
‹#›
Breaking a Loop
int[] numbers = { 1, 5, 3, 4, 2 };
int i = 0, key = 3;
if (i < numbers.length)
System.out.println("Key is found in the array");
else
System.out.println("Key is NOT!");
‹#›
Object-Oriented Paradigm
Centered on the concept of the object
Object
Physical entity
Truck
Conceptual entity
Bank Account
Software entity
Chemical
Process
Linked List
OOAD Using the UML - Introduction to Object Orientation, v 4.2, 1998-1999 Rational Software ‹#›
Basic Principles of Object Orientation
Object Orientation
Encapsulation
Abstraction
Modularity
Hierarchy
OOAD Using the UML - Introduction to Object Orientation, v 4.2, 1998-1999 Rational Software ‹#›
Abstraction is one of the
What is Abstraction? fundamental ways that
we as humans cope with
complexity.
Salesperson
Not saying
which salesperson
just a salesperson in general!
Product
Customer
Dahl, Dijkstra, and Hoare suggest that “abstraction arises from a recognition of similarities
between certain objects, situations, or processes in the real world, and the decision to
concentrate upon these similarities and to ignore for the time being the differences”.
OOAD Using the UML - Introduction to Object Orientation, v 4.2, 1998-1999 Rational Software ‹#›
What is Abstraction?
‹#›
What is Abstraction?
Abstraction is the process of removing physical, spatial, or
temporal details or attributes in the study of objects or
systems in order to more closely attend to other details of
interest.
‹#›
What is Encapsulation?
¢ Hide implementation from clients
§ Clients depend on interface
Information Hiding:
How does an object encapsulate?
What does it encapsulate?
Abstraction and encapsulation are complementary concepts: Abstraction focuses on the observable
behavior of an object, whereas encapsulation focuses on the implementation that gives rise to this
behavior.
OOAD Using the UML - Introduction to Object Orientation, v 4.2, 1998-1999 Rational Software ‹#›
What is Encapsulation?
‹#›
What is Modularity?
The breaking up of something complex into manageable pieces.
Order Entry
Billing
‹#›
What is Hierarchy?
Increasing
abstraction Vehicle
Elements at the same level of the hierarchy should be at the same level of
abstraction. ‹#›
What is Really an Object?
Formally, an object is a concept, abstraction, or thing with sharp
boundaries and meaning for an application.
‹#›
What is a Class?
A class is a description of a group of objects with common
properties (attributes), behavior (operations), relationships, and
semantics
An object is an instance of a class
‹#›
Example Class
Class
Course
Attributes Behavior
Name Add a student
Location Delete a student
a + b = 10
Days offered Get course roster
Credit hours Determine if it is full
Start time
End time
OOAD Using the UML - Introduction to Object Orientation, v 4.2, 1998-1999 Rational Software ‹#›
Representing Classes
A class is represented using a compartmented rectangle
Professor a + b = 10
Professor Clark
OOAD Using the UML - Introduction to Object Orientation, v 4.2, 1998-1999 Rational Software ‹#›
Class Compartments
A class is comprised of three sections
The first section contains the class name
The second section shows the structure (attributes)
The third section shows the behavior (operations)
OOAD Using the UML - Introduction to Object Orientation, v 4.2, 1998-1999 Rational Software ‹#›
How Many Classes do you See?
OOAD Using the UML - Introduction to Object Orientation, v 4.2, 1998-1999 Rational Software ‹#›
Relationship between Classes and Objects
A class is an abstract definition of an object
It defines the structure and behavior of each object in the
class
It serves as a template for creating objects
Objects are grouped into classes
Objects Class
Professor
Professor Mellon
Professor Smith
Professor Jones
‹#›
State of an Object (property or attribute)
The state of an object encompasses all of the (usually static)
properties of the object plus the current (usually dynamic)
values of each of these properties.
Object Attribute
Value
Class
CourseOffering
number = 101
startTime = 900
CourseOffering endTime = 1100
Attribute
number
startTime
endTime CourseOffering
number = 104
startTime = 1300
endTime = 1500
‹#›
Behavior of an Object (operation or method)
Behavior is how an object acts and reacts, in terms of its state
changes and message passing.
Class CourseOffering
addStudent
Operation deleteStudent
getStartTime
getEndTime
‹#›
Identity of an Object
Each object has a unique identity, even if the state is identical to
that of another object.
OOAD Using the UML - Introduction to Object Orientation, v 4.2, 1998-1999 Rational Software ‹#›
Sample Class: Automobile
Attributes
manufacturer’s name
model name
year made
color
number of doors
size of engine
Methods
Define attributes (specify manufacturer’s name, model, year, etc.)
Change a data item (color, engine, etc.)
Display data items
Calculate cost
‹#›
Sample Class: Circle
Attributes
Radius
Center Coordinates
X and Y values
Methods
Define attributes (radius and center coordinates)
Find area of the circle
Find circumference of the circle
‹#›
Sample Class: Baby
Attributes
Name
Gender
Weight
Decibel
# poops so far
Methods
Get or Set specified attribute value
Poop
‹#›
Summary
So far, we covered basics of objects and object oriented
paradigm.
We tried to think in terms of objects.
‹#›
Acknowledgments
The course material used to prepare this presentation is mostly
taken/adopted from the list below:
Software Enginering (9th ed) by I.Sommerville, Pearson,
2011.
Object Oriented Analysis and Design with Applications, Grady
Booch, Robert A. Maksimchuk, Michael W. Engle, Bobbi J.
Young, Jim Conallen and Kelli A. Houston, Addison Wesley,
2007.
OOAD Using the UML - Introduction to Object Orientation, v
4.2, 1998-1999 Rational Software
Java - An Introduction to Problem Solving and Programming,
Walter Savitch, Pearson, 2012.
Ku-Yaw Chang, Da-Yeh University.
‹#›