Download Programlama ve Nesneler

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Object Oriented Programming
Lecture 2: Object Oriented Design
+
Variables and Basics
Mustafa Emre İlal
[email protected]
Recap
• Architects and programming
• A Program – Programming languages
• Java
– Portable
– Purely object oriented
– Comprehensive library
Today
• 1. Half: Object Oriented Design
– Software Engineering
• 2. Half: Variables and basics
– Your first program in Java
1: Object Oriented Design
–
–
–
–
Too many new concepts
No examples
Do not expect to grasp all immediately
You should ask questions
– Thinking in Java – First half of Chapter 1
– www.omg.org/uml
Programming
• Problem solving
• Architecture = Programming?
• Constrained by mathematical models
Modeling
• Design (mathematical)
• Description
Input
data
– Architectural problem
• Mass models
• Working models
• Presentation models
CPU
Memory
– Software problem
• Structural models (data)
• Functional models (behavior)
Output
result
UML
• Unified Modeling Language
• Booch, Rumbaugh and Jacobson
• Common “language” for describing object
oriented systems
• Representation is mostly through visual diagrams
UML
• Necessary for large, complex systems
• Documents entire software development process
– Use cases: help formalize requirements
– Interaction diagrams: "sequence diagram",
"collaboration diagrams” document system behavior
– Class diagrams: provide specification for data structure
Use Cases
• Specific scenarios
Interaction
• Sequence Diagram
• Collaboration Diagram
Class Diagrams
• Data Structures
Objects and Classes
• Data in programming languages
– Primitive types (e.g. integers)
– Arrays or collections
• Objects (agents)
–
–
–
–
–
Include both Data + Behavior = “Encapsulation”
All belong to some “Class” (classification)
Classes are templates for objects
Each object is an “Instance” of the Class it belongs to
An object can include other objects
Object – TV
• Data (Properties )
–
–
–
–
–
–
–
Screen size
Weight
Number of channels
Contrast setting
Brightness setting
Channel currently being viewed
The existence of the required voltage
Object – TV
• Behavior (methods / functions)
– Turning it on/off
– Remote commander
•
•
•
•
Numeric pad
Channel switcher
Sound/Color/Setting dial
Menu
• Each button press is a “message” from the user to
the object.
Messaging
• Every message
– Activates a process that will prepare a suitable reply to
the message. (method invocation)
– Needs to include the information necessary to complete
the requested action. (parameters/arguments)
– Is answered with a proper reply (the return value)
unless it requests none (a void reply)
Objects
• Encapsulation
– Properties
– Methods
• Interface
• Information Hiding
UML:
TV
screenSize
weight
noChannels
contrastSetting
brightnessSetting
currentChannel
suppliedVoltage
isTurnedOn
turnOn()
changeChannel(newChannel)
lowerVolume()
increaseVolume()
mute()
lowerContrast()
increaseContrast()
showMenu()
Information Hiding
• The object interface is a “contract” between the
developer of the class and the other developers
• There needs to be a way to be able to make
changes to the class without breaking contract.
• Java keywords for access:
–
–
–
–
public
protected
private
“default" or “friendly”– when nothing is specified
Reuse
• Once a class is designed and developed, it should
be used in many different projects.
• Reuse:
– Association, aggregation, composition
– Inheritance
– Libraries, APIs
Object Composition
• Association (has-a relationship)
• Aggregation (part-of relationship)
Structural System
Column
Site
Beam
Slab
Inheritance
• superclass – subclass
• Java: "extends" keyword (“class A extends B")
Structural System
Site
StrSysElement
Column
Beam
Slab
Inheritance
• Also called “generalization”
• Java allows only a single superclass
• Subclass automatically includes all properties and
methods of the superclass except private ones.
• Methods can be rewritten in which case the
behavior of subclass is altered. (“overriding”)
– Basis of “Polymorphism”
Even more confusion
• Abstract classes
– Classes that describe concepts rather than concrete objects.
• Interfaces
– Specifications (list of methods) for objects in order to be
considered for certain tasks.
– A class can adhere to multiple interfaces.
• Class variables and methods
– Properties and methods that are not for any objects (the instances
of a class) but rather accessed centrally through the class definition
itself. They are specified by the "static” keyword.
2: Variables and Basics
• Variables
– Primitive types
– Classes and objects
– Your first program
• Basics
– Types
– Operators
• Thinking in Java – Chapter 2 - 3
Variables
• Primitive Types
• Arrays
• Objects
Primitive Types
• Java’s primitives
–
–
–
–
–
–
–
–
byte : -128 to 127 (8 bits)
short : -32,768 to 32,767 (16 bits)
int : -2,147,483,648 to 2,147,483,647 (32 bits)
long :-9,223,372,036,854,775,808 to
9,223,372,036,854,775,807 (64 bits)
float : 1.40129846432481707e-45 to
3.40282346638528860e+38 (positive or negative) (32 bits)
double : 4.94065645841246544e-324d to
1.79769313486231570e+308d (positive or negative) (64 bits)
boolean : true/false (1 bit)
char : Unicode 0 to 65,535 (16 bits)
References
Primitives
1
0
0
1
0
0
0
1
+/-
26
25
24
23
22
21
20
byte a = 17;
float b = 34.56;
References (pointers)
c
Object c = new Object();
a
17
b
34.56
c
Primitives
a
3
b
6
a = b;
a
6
b
6
b = 7;
a
6
b
7
int a = 3;
int b = 6;
References
Object x;
Object y;
x = new Object();
y = x;
x
y
Object
// we do not get two Objects
y = x.clone();
Object
Arrays
• Array
• A collection of a known number of variables of
the same type.
• In Java, it is a reference type – an object
Scope of Variables
• { } curly brackets create scope
• Primitives are erased from memory once the
process leaves their scope
• Objects are not affected by scope. They are erased
only when there are no more referances pointing
to them
Scope
{
int x; //definition
{
int q = 96; //definition
x = q; // OK
}
x = q; // error! – ‘q’ is out of scope
}
Classes and Objects
• Class is the definition for a new type
• Instances of the class, objects, are created (instantiated)
with the “new” operator.
• Access to properties and methods of an object is by placing
a ‘.’ character between the object reference and the
property or method name.
anObject.anIntVariable = 5;
anObject.aMethod();
anObject.anotherObject.aMethod();
• “object oriented”
static
• Properties and methods that are only for the Class
and will not be a part of the instances (objects) are
defined with the keyword “static”
• Two common uses
– Variables for keeping track of all objects belonging to a
class.
– Methods that need to be called without any objects.
Packages
• “File system” to avoid naming conflicts between source
codes from different developers.
• In order to use a class in your code, you need to specify the
package where it belongs by preceeding the class name
with the package name.
java.util.ArrayList a = new java.util.ArrayList();
• import statement provides a shorthand for the source code.
import java.util.ArrayList;
...
ArrayList a = new ArrayList();
• import java.lang.*;
statement above is implied for every java program and
need not be included.
Your First Program
• The famous "Hello World"
• Java is case-sensitive
• public static void main (String[] args)
is the entry point for the program
• “javac.exe fileName.java” (include the suffix)
> javac HelloWorld.java
• “java.exe classToRun” (class name that includes
the main() method without suffix )
> java HelloWorld
Operators
Casting Operator
• Java is "strongly-typed"
• Transfer of value between two variables of different types
is a “cast”
– As long as there is no loss of information, Java will automatically
execute the statement. (widening)
– If a loss of data is possible, the programmer needs to take
responsibility and force the “cast”(narrowing)
int a = 5;
float b = 3.56;
b = a;
// automatic
a = b;
//error. Will not compile
a = (int)b;
// "cast" – programmer’s initiative
Object Cast
• Same thing for Objects
• Superclass – subclass relationships
– An object can automatically be treated as an instance of
its superclass (generalization)
– A “cast” operator is required if an object is to be used
as an instance of its subclass (specialization)
Arithmetic operators
• General rules apply
+ : a + b : addition
- : a – b : subtraction
* : a * b : multiplication
/ : a / b : division
% : a%b : modulus (remainder after a/b)
• <left operand> <operator> <right operand>
result is the return value
Assignment operator
• "="
• DIFFERENT from math:
a = a + 5;
first, the right side is resolved, then is assigned to
the left side.
• IMPORTANT: it does not mean “Are they equal?”
Shorthand for increment/decrement
• ++a; a = a+1; equivalent (shorthand notation)
–
–
–
–
++counter; use the value after incrementing
--counter ; use the value after decrementing
counter++; use the value first, then increment
counter--; use the value first, then decrement
Comparison operators
• The operators below compare the right operand with the
left operand and return a boolean value (true or false)
–
–
–
–
–
–
> : a >b;
>= : a>=b;
< : a<b;
<= :a<=b;
== : a==b;
!= : a!=b;
is a greater than b?
is a greater than or equal to b?
is a less than b?
is a lass than or equal to b??
is a equal to b? (note the double equals)
is a not equal to b?
• IMPORTANT: You should not compare objects with these
operators.
Conditional operators
• Conditional operators return a boolean result
depending on the evaluation of the two boolean
components left and right.
–
–
–
–
&& : a && b; return true if both a and b are true.
|| : a || b; return true if a or b is true.
! : !a; returns the opposite of a (“not a”)
& : a & b; same as ‘&&’ operator except that it forces
both components to be evaluated even if the
first term is false.
– | : a | b; same as ‘||’ operator except that it forces
both components to be evaluated even if a is true.
Promotion Rule
• If an operator is used on two values which are of
different types, the ‘smaller’ of the two types is
promoted to the ‘larger’ type and then the
evaluation is performed. For example,
3.1415 * 7
• 3.1415 is a float and 7 is an int. Since int is
‘smaller’, it is converted to a float 7.0 and then the
numbers are multiplied.
Operator Precedence
• Order of evaluation
–
–
–
–
–
–
()
++, -*/%
+< <= > >=
== !=
Unexpected Results
• Computers follow the rules of type conversion and
operator precedence strictly in evaluating
expressions.
• Best to use parenthesis to clarify the order of
evaluation.
• float a = 3 / 2;
what is the value of a?
– 1 (not 1.5!)
• float a = (float)3/(float)2;
• float a = (float)3/2;
• float a = 3.0/2.0;
// automatic promotion
// wise
Wrapper Classes
• For each of the primitive data types, Java also provides a
useful ‘wrapper’ Class in java.lang package
–
–
–
–
–
–
int : Integer
long : Long
float : Float
double : Double
char : Character
boolean : Boolean
• The wrapper classes provide a bridge between primitive
data types and Objects
java.lang.Math
• The Math Class provides some basic mathematical
functions. Examples:
–
–
–
–
–
static double sqrt(double a)
static double random()
static double sin()
static double abs(double a)
static double max(double a, double b)
Characters
• Characters (char) were “digitized” based on the
ASCII standard with a 256 character limit.
• Java now uses the UNICODE standard that offers
65,536 characters for internationalization.
• Numeric operators work with char types in the
same manner as int types.
• char c = 'A'; UNICODE value 65
• C++ ;
UNICODE value 66 which is 'B'
java.lang.String
• Input/output using single characters is difficult
• Java makes use of STRINGs, Objects that manipulate an
array of characters. It comes with the API.
• Some methods:
–
–
–
–
boolean compareTo(String anotherString)
String subString(int beginIndex, int endIndex)
int length()
String concat(String str)
• Some useful shortcuts for Strings:
– Quotes instantiate a new String object
String s = “Message";
– Addition operator concatenates two Strings together
String s = s + "lar uzatılabilir";
Assignment 1
•
Write a “Circle” class
–
–
•
Two methods to calculate its area and circumference
A third method to find out if a given point is inside the circle
Write a “CircleApplication” class (separate .java file)
–
–
Only a main() method
Should create 5 circles, and a single point. It should output the
following about each:
•
•
•
•
Coordinates for its center
Area
Circumference
If the point lies inside or outside the circle
Assignment 2
• Write a Point class
– Should have x and y coordinate values (only 2D)
– Update the Circle and CircleApplication classes to
make use of this Point class.
Next Week
• Preperation: Thinking in Java Chapter 4-6