Vous êtes sur la page 1sur 61

O B J E C T O R I E N T E D

P R O G R A M M I N G
Course 2
Loredana STANCIU
loredana.stanciu@aut.upt.ro
Room B616
A CLOSER LOOK AT THE "HELLO WORLD!"
APPLICATION
/** * The HelloWorldApp class implements an
application that simply prints "Hello
World!" to standard output. */
class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!");
// Display the string. } }
Components:
Source code comments
The HelloWorld class definition
The main method
A CLOSER LOOK AT THE "HELLO WORLD!"
APPLICATION
Three kinds of comments:
/* text */ the compiler ignores everything from
/* to */
/** documentation */ the compiler ignores
everything from /** to */. The javadoc tool
creates automatically generated documentation
// text the compiler ignores everything from // to
the end of line
A CLOSER LOOK AT THE "HELLO WORLD!"
APPLICATION
In the Java programming language, every
application must contain a main method
whose signature is:
public static void main(String[] args)
The main method:
the entry point for an application
will subsequently invoke all the other methods
required in the program
accepts a single argument: an array of elements of
type String
WHAT IS AN OBJECT?
Real-world objects share two characteristics:
State: dog (name, color, breed, hungry), bicycle
(current gear, current pedal cadence, current
speed)
Behavior: dog (barking, fetching, wagging tail),
bicycle (changing gear, changing pedal cadence,
applying brakes)
Two questions regarding the objects:
What possible states can this object be in?
What possible behavior can this object perform?
WHAT IS AN OBJECT?
Software objects:
Field
Method:
operate on an object's
internal state
serve as the primary
mechanism for object-
to-object
communication
WHAT IS AN OBJECT?
Benefits of using objects:
Modularity: independence between source codes,
objects can be easily passed around inside the
system
Information-hiding: interaction with objects
methods, the details remain hidden
Code reuse: objects created by other programmers
Pluggability and debugging ease: a problematic
object can be removed and replaced with other
object
WHAT IS A CLASS?
In the real world: many individual objects all of
the same kind
Ex: a certain bicycle is an instance of the class
of objects known as bicycles
A class is the blueprint from which individual
objects are created
WHAT IS A CLASS
class Bicycle {
int cadence = 0;
int speed = 0;
int gear = 1;
void changeCadence(int newValue) {
cadence = newValue; }
void changeGear(int newValue) {
gear = newValue; }
void speedUp(int increment) {
speed = speed + increment; }
void applyBrakes(int decrement) {
speed = speed - decrement; }
void printStates() {
System.out.println("cadence:"+cadence+" speed:"+speed+" gear:"+gear); }
}
WHAT IS A CLASS
class BicycleDemo {
public static void main(String[] args) {
// Create two different Bicycle objects
Bicycle bike1 = new Bicycle();
Bicycle bike2 = new Bicycle();
// Invoke methods on those objects
bike1.changeCadence(50);
bike1.speedUp(10);
bike1.printStates();
bike2.speedUp(10);
bike2.changeGear(2);
bike2.changeCadence(40);
bike2.changeGear(3);
bike2.printStates(); } }
WHAT IS AN INHERITANCE?
Different kinds of
objects often have a
certain amount in
common with each
other
One superclass and
many subclasses
class MountainBike extends Bicycle {
// new fields and methods defining a
mountain bike would go here
}
WHAT IS AN INTERFACE?
A group of related methods with empty bodies
interface Bicycle {
void changeCadence(int newValue);
void changeGear(int newValue);
void speedUp(int increment);
void applyBrakes(int decrement);
}
class ABicycle implements Bicycle {
// implemented as before
}
THE JAVA PROGRAMMING LANGUAGE
VARIABLES
Instance Variables (Non-Static Fields): objects
individual state: int x;
Class Variables (Static Fields): is exactly one
copy of the variable: static int x;
Local Variables: belonging to a method
Parameters: the arguments of a method
THE JAVA PROGRAMMING LANGUAGE
NAMING VARIABLES
Case-sensitive
An unlimited-length sequence of Unicode letters and
digits, beginning with a letter
Use full words instead of cryptic abbreviations
The name you choose must not be a keyword or
reserved word
The name
only one word: speed
more than one word: currentSpeed
constant value: NUM_CAR
THE JAVA PROGRAMMING LANGUAGE
PRIMITIVE DATA TYPES
The Java programming language is strongly-
typed (statically typed): int speed = 1;
A primitive type predefined by the language
and named by a reserved keyword
byte 8 b float 32 b
short 16 b double 64 b
int 32 b boolean: true, false
long 64 b char 16 b
THE JAVA PROGRAMMING LANGUAGE
PRIMITIVE DATA TYPES
Default values for primitives types
Data Type Default Value (for fields)
byte 0
short 0
int 0
long 0L
float 0.0f
double 0.0d
char '\u0000'
String (or any object) null
boolean false
THE JAVA PROGRAMMING LANGUAGE
PRIMITIVE DATA TYPES
The new keyword isn't used when initializing a
variable of a primitive type
A literal the source code representation of a
fixed value
boolean result = true;
char capitalC = 'C';
b = 100;
short s = 10000;
int i = 100000;
THE JAVA PROGRAMMING LANGUAGE
PRIMITIVE DATA TYPES
Always use 'single quotes' for char literals and
"double quotes" for String literals
Special escape sequences for char and String
literals:
\b (backspace), \t (tab), \n (line feed), \f (form
feed), \r (carriage return), \" (double quote), \'
(single quote), and \\ (backslash)
A special null literal may be assigned to any
variable, except variables of primitive types
THE JAVA PROGRAMMING LANGUAGE
ARRAYS
A container object that holds a fixed number
of values of a single type
The length established when the array is
created and cannot be changed
THE JAVA PROGRAMMING LANGUAGE
ARRAYS
Declaration: int[] anArray;
Creation: anArray = new int[10];
Accessing an element: anArray[0] = 2;
Declaration and initialisation: int[] anArray
= {100, 200, 300, 400, 500, 600,
700, 800, 900, 1000};
multidimensional array: String[][]names;
determine the size: anArray.length
THE JAVA PROGRAMMING LANGUAGE
COPY ARRAYS
public static void arraycopy(Object src, int srcPos,
Object dest, int destPos, int length)
class ArrayCopyDemo {
public static void main(String[] args) {
char[] copyFrom = { 'd', 'e', 'c', 'a',
'f', 'f', 'e', 'i', 'n', 'a', 't', 'e'};
char[] copyTo = new char[7];
System.arraycopy(copyFrom,2, copyTo, 0,7);
System.out.println(new String(copyTo));
} }
caffein
THE JAVA PROGRAMMING LANGUAGE
OPERATORS
Special symbols that perform specific
operations on one, two, or three operands,
and then return a result
Operators with higher precedence are
evaluated before operators with relatively
lower precedence
THE JAVA PROGRAMMING LANGUAGE
OPERATORS
Operator Precedence
Operators Precedence
postfix expr++ expr--
unary ++expr --expr +expr -expr ~ !
multiplicative * / %
additive + -
shift << >> >>>
relational < > <= >= instanceof
equality == !=
bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
logical AND &&
logical OR ||
ternary ? :
assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=
THE JAVA PROGRAMMING LANGUAGE
OPERATORS
The Simple Assignment Operator
int cadence = 0;
int speed = 0;
int gear = 1;
The Arithmetic Operators
+ additive operator (also used for String
concatenation)
- subtraction operator
* multiplication operator
/ division operator
% remainder operator
THE JAVA PROGRAMMING LANGUAGE
OPERATORS
The Unary Operators
+ Unary plus operator; indicates positive value
(numbers are positive without this, however)
- Unary minus operator; negates an expression
++ Increment operator; increments a value by 1
-- Decrement operator; decrements a value by 1
! Logical complement operator; inverts the value of a
boolean
THE JAVA PROGRAMMING LANGUAGE
OPERATORS
The Equality and Relational Operators
== equal to
!= not equal to
> greater than
>= greater than or equal to
< less than
<= less than or equal to
The Conditional Operators
&& Conditional-AND
|| Conditional-OR
?: Ternary operator
THE JAVA PROGRAMMING LANGUAGE
OPERATORS
The Type Comparison Operator instanceof
compares an object to a specified type
test if an object is an instance of a class, an
instance of a subclass, or an instance of a class
that implements a particular interface
obj1 instanceof Parent
obj1 instanceof Child
THE JAVA PROGRAMMING LANGUAGE
EXPRESSIONS
A construct made up of variables, operators,
and method invocations
The data type of the value returned depends on
the elements used
Use balanced parenthesis: ( and ) to create
unambiguous expressions
x+y/2 //ambiguous
(x+y)/2 //unambiguous
THE JAVA PROGRAMMING LANGUAGE
STATEMENTS
Are equivalent to sentences in natural languages
Forms a complete unit of execution
Types of expressions that can be made into a
statement by terminating the expression with a
semicolon (;):
Assignment expressions : aValue=3;
Any use of ++ or -- : aValue++;
Method invocations: i.changeValue();
Object creation expressions : Integer I = new
Integer();
THE JAVA PROGRAMMING LANGUAGE
STATEMENTS AND BLOCKS
Statements:
Expression statements
Declaration statements (declares a variable)
Control flow statements (regulate the order in which
statements get executed)
A block is a group of zero or more statements
between balanced braces
THE JAVA PROGRAMMING LANGUAGE
CONTROL FLOW STATEMENTS
Break up the flow of execution by employing
decision making, looping, and branching
The if-then-else Statement
void applyBrakes(){
if (isMoving)
currentSpeed--;
else
System.out.println("The bicycle has
already stopped!");
}
THE JAVA PROGRAMMING LANGUAGE
CONTROL FLOW STATEMENTS
The switch Statement
Allows for any number of possible execution paths
int month = 3;
switch (month) {
case 1: System.out.println("January"); break;
case 2: System.out.println("February"); break;
case 3: System.out.println("March"); break;
.
case 12: System.out.println("December"); break;
default: System.out.println("Invalid
month.");break; }}
THE JAVA PROGRAMMING LANGUAGE
CONTROL FLOW STATEMENTS
The while and do-while Statements
Executes a block of statements while a particular
condition is true
while (expression) { do {
statement(s) statement(s)
} } while (expression);
The difference between do-while and while is that
do-while evaluates its expression at the bottom of
the loop instead of the top
THE JAVA PROGRAMMING LANGUAGE
CONTROL FLOW STATEMENTS
class WhileDemo {
public static void
main(String[] args){
int count = 1;
while (count < 11) {
System.out.println(
"Count is: " +
count);
count++; }
}
}
class WhileDemo {
public static void
main(String[] args){
int count = 1;
do {
System.out.println
("Count is: " +
count);
count++; }
} while (count < 11)
}
THE JAVA PROGRAMMING LANGUAGE
CONTROL FLOW STATEMENTS
The for Statement
A compact way to iterate over a range of values
for (initialization; termination; increment) {
statement(s)
}
The initialization expression initializes the loop; it's executed
once, as the loop begins.
When the termination expression evaluates to false, the loop
terminates.
The increment expression is invoked after each iteration
through the loop; it is perfectly acceptable for this expression to
increment or decrement a value.
THE JAVA PROGRAMMING LANGUAGE
CONTROL FLOW STATEMENTS
The for Statement
class ForDemo {
public static void main(String[] args){
for(int i=1; i<11; i++){
System.out.println("Count is: " + i);
}
}
}
Infinite loop: for( ; ; ) {//your code goes here}
enhanced for statement
int[] numbers = {1,2,3,4,5,6,7,8,9,10};
for (int item : numbers)
{
System.out.println("Count is: " + item);
}
THE JAVA PROGRAMMING LANGUAGE
BRANCHING STATEMENTS
The break Statement : unlabeled and labeled
int[] arrayOfInts = { 32, 87, 3, 589, 12, 1076, 200};
int searchfor = 12;
int i;
boolean foundIt = false;
for (i = 0; i < arrayOfInts.length; i++)
{
if (arrayOfInts[i] == searchfor)
{
foundIt = true;
break;
}
}
THE JAVA PROGRAMMING LANGUAGE
BRANCHING STATEMENTS
int[][] arrayOfInts = { { 32, 87, 3, 589 },
{ 12, 1076, 2000, 8 },
{ 622, 127, 77, 955 } };
int searchfor = 12; int j = 0; boolean foundIt = false;
search:
for (int i = 0; i < arrayOfInts.length; i++)
{
for (j = 0; j < arrayOfInts[i].length; j++)
{
if (arrayOfInts[i][j] == searchfor)
{
foundIt = true;
break search;
}
}
}
THE JAVA PROGRAMMING LANGUAGE
BRANCHING STATEMENTS
The continue statement
Skips the current iteration
String searchMe = "peter piper picked a peck of
pickled peppers";
int max = searchMe.length();
int numPs = 0;
for (int i = 0; i < max; i++)
{
//interested only in p's
if (searchMe.charAt(i) != 'p') continue;
//process p's
numPs++;
}
THE JAVA PROGRAMMING LANGUAGE
BRANCHING STATEMENTS
The return statement
exits from the current method
Can return a value:
return ++count;
Or nothing:
return;
THE JAVA PROGRAMMING LANGUAGE
CLASSES
The class declaration:
class MyClass {
//field, constructor, and method
declarations
}
class MyClass extends MySuperClass
implements MyInterface{
//field, constructor, and method
declarations
}
THE JAVA PROGRAMMING LANGUAGE
CLASSES
Several kinds of variables:
Member variables in a class fields.
Variables in a method or block of code local variables.
Variables in method declarations parameters.
Declaring member variable:
Zero or more modifiers, such as public or private
The field's type.
The field's name.
public int speed;
private int counter;
public String name;
THE JAVA PROGRAMMING LANGUAGE
CLASSES
Defining methods
public double calculate(double length,
double width) { //do the calculation here }
Definition: Two of the components of a method declaration
comprise the method signaturethe method's name and the
parameter types.
Method names a verb in lowercase or a multi-word name
that begins with a verb in lowercase
runFast getBackground
compareTo setX
isEmpty
THE JAVA PROGRAMMING LANGUAGE
CLASSES
Overloading methods
Different method signatures
public class DataDraw {
...
public void draw(String s)
{ ... }
public void draw(int i)
{ ... }
public void draw(double f)
{ ... }
public void draw(int i, double f)
{ ... }
}
THE JAVA PROGRAMMING LANGUAGE
CLASSES
Constructors
use the name of the class and have no return type
a no-argument, default constructor for any class without
constructors
public Point(int xCoord, int yCoord)
{
x = xCoord;
y = yCoord;
}
Point p1 = new Point(2,3);
THE JAVA PROGRAMMING LANGUAGE
PASSING INFORMATION TO A METHOD OR A
CONSTRUCTOR
Parameters refers to the list of variables in a
method declaration.
Arguments are the actual values that are
passed in when the method is invoked.
When you invoke a method, the arguments
used must match the declaration's parameters
in type and order (passed by value).
public Polygon polygonFrom(Point[]
corners)
{ // method body goes here }
THE JAVA PROGRAMMING LANGUAGE
OBJECTS
A typical Java program creates many objects,
which interact by invoking methods
Point p1 = new Point(2,3)
Declaration: associate a variable name with an object
type.
Instantiation: the new keyword operator that
creates the object.
Initialization: the constructor
THE JAVA PROGRAMMING LANGUAGE
OBJECTS
The new operator:
instantiates a class by allocating memory for a new
object and returning a reference to that memory.
invokes the object constructor
"instantiating a class" means the same thing
as "creating an object
THE JAVA PROGRAMMING LANGUAGE
OBJECTS
Initializing an object:
class Point {
private int x = 0;
private int y = 0;
//constructor
public Point(int a, int b) {
x = a;
y = b;
}
}
THE JAVA PROGRAMMING LANGUAGE
OBJECTS
Initializing an object:
Point originOne = new Point(23, 94);
THE JAVA PROGRAMMING LANGUAGE
OBJECTS
Referencing an object's fields or methods
objectReference.fieldName
originOne.x
objectReference.methodName(argume
ntList);
or
objectReference.methodName();
originOne.setValueX(3);
int height = new Rectangle().height;
new Rectangle(100, 50).getArea();
THE JAVA PROGRAMMING LANGUAGE
OBJECTS
The Garbage Collector
The Java runtime environment (JRE) deletes
objects when it determines that they are no
longer being used
An object is eligible for garbage collection when
there are no more references to that object.
The garbage collector does its job automatically
and periodically.
THE JAVA PROGRAMMING LANGUAGE
The this Keyword
a reference to the current object
class Point {
private int x = 0;
private int y = 0;
//constructor
public Point(int x, int x) {
this.x = x;
this.y = y;
}
}
THE JAVA PROGRAMMING LANGUAGE
The this Keyword
an explicit constructor invocation
public class Rectangle {
private int x, y;
private int width, height;
public Rectangle() { this(0, 0, 0, 0); }
public Rectangle(int width, int height) {
this(0, 0, width, height); }
public Rectangle(int x, int y, int width, int
height) {
this.x = x; this.y = y;
this.width = width; this.height = height; }
... }
THE JAVA PROGRAMMING LANGUAGE
Controlling Access to Members of a Class
At the top levelpublic, or package-private (no explicit
modifier).
At the member levelpublic, private, protected, or
package-private (no explicit modifier).
Access Levels
Modifier Class Package Subclass World
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N
THE JAVA PROGRAMMING LANGUAGE
Tips on Choosing an Access Level:
Use the most restrictive access level that
makes sense for a particular member.
Use private unless you have a good reason not
to.
Avoid public fields except for constants.
Public fields tend to link to a particular
implementation and limit the flexibility in
changing the code.
THE JAVA PROGRAMMING LANGUAGE
Class Variables
Every object have distinct copies of instance
variables
To have variables that are common to all
objects: static keyword in front of the name
=>static fields or class variables
private static int counter = 0;
p1.counter
Point.counter
THE JAVA PROGRAMMING LANGUAGE
Class Methods
ClassName.methodName(args)
Common use for static methods: to access static
fields
public static int getNumOfPoints()
{
return counter;
}
THE JAVA PROGRAMMING LANGUAGE
Constants
The static modifier, in combination with the
final modifier
static final double PI =
3.141592653589793;
Constants defined in this way cannot be
reassigned
Name of constant values are spelled in
uppercase letters
THE JAVA PROGRAMMING LANGUAGE
EnumTypes
a type whose fields consist of a fixed set of
constants
public enum Day{
SUNDAY, MONDAY, TUESDAY,
WEDNESDAY, THURSDAY, FRIDAY,
SATURDAY
}
Day.MONDAY
REFERENCES
The Java Tutorials. Getting Started.
http://java.sun.com/docs/books/tutorial/getStarted
/index.html
The Java Tutorials. Learning the Java Language.
http://java.sun.com/docs/books/tutorial/java/TOC.
html

Vous aimerez peut-être aussi