You are on page 1of 62

3.

Object Oriented Programming 1


(programarea orientat pe obiecte)
1. Justification
2. Objects
3. Classes
4. Fields
5. Methods
6. Constructors
7. Domains and visibility
8. Object creation and destruction
9. Inheritance
10. Aggregation

Tiberiu Leia: Software Engineering Object Oriented Programming

1. Justification
Object Oriented Programming (OOP) is an evolution of structured
programming.
Advantages:
development of software project is more easier
code reusing
divide the team work
program debugging
program maintenance, etc.

Tiberiu Leia: Software Engineering Object Oriented Programming

Characteristics:
Everything is an object or a class
A program is a bunch of objects telling each other what to do by sending
messages. Classes are accepted too.
Each object has its own memory made up of other objects
Every object has a type (class)
All objects of a particular type can receive the same messages.
An object has an interface=the request you can make of an object
the methods it implements.
The objects can be manipulated using their references.

Tiberiu Leia: Software Engineering Object Oriented Programming

2. Objects
An object is a block of data and operations. The executions of operations
depend on the objects states.
The object has variables (attributes) instantiated and methods to manipulate
them, composing an atomic unit.
Usually only the services are visible. The implementations are concealed
partially or totally. Data and methods are encapsulated.
method = a way to do something = a service provided for other objects
Each object has a memory area. It is allocated at the object creation
(instantiation). The variables storied in the object memory area are named
instance variables. (variabile de instan)

Tiberiu Leia: Software Engineering Object Oriented Programming

Encapsulation = the
procedure to pack the
objects data and methods
together. (ncapsulare)

Object
Message

An object has a
visible part and a hidden
part. The encapsulation
conceals the object
implementation and
forbid the access to data
and methods that are not
public.
Operation
solicitations are
method calls = send
messages

Method

Answer

Data

Fig. 3.1. Object structure

Tiberiu Leia: Software Engineering Object Oriented Programming

The messages contain:


different primitive data types simple data;
other objects = reference type data
registrations
The object chooses the method that fulfils the requested service.
polymorphism = methods accept interchangeable objects as parameters
methods implement the object behaviors
object creation a name is given to a region of storage
A method is a name for an action.

Tiberiu Leia: Software Engineering Object Oriented Programming

3. Classes
Class1

class = a template for object creation (or


instantiation). The objects have specified
properties.
Class = a structure that defines data and
methods
A class is a classifier which describes a set of
objects that share the same
features
constraints
semantics (meaning).

+at1: int
+at2: float
+met1(): int
+met(): float

Class2
+at3: double
+at4: Class1
+met3(): double
+met4(): Class1

Class defines the object internal structure (attributes or properties) and describes its
functionality (behavior) by methods
A class is a definition of properties common to a group of objects. class members
Tiberiu Leia: Software Engineering Object Oriented Programming

class members

ClassName
Data

ClassName = identifier

fields
Message

Package
PackageName.ClassName

setData
methods
getData
Methods

Answer

Constructor

s
Method

main
General structure of a class
Tiberiu Leia: Software Engineering Object Oriented Programming

Features of a class are attributes and operations.

Attributes of a class are represented by instances of property that are owned by the class. Some
of these attributes may represent the navigable ends of binary associations.

Objects of a class must contain values for each attribute that is a member of that class.

A property is a structural feature which could represent an attribute of a classifier or an attribute


of association.

Tiberiu Leia: Software Engineering Object Oriented Programming

Any non-abstract class can be instantiated.


When a class is instantiated
- the property represents a value or collection of values associated with an instance of one or
more types.

The set of classifiers is called the context for the property.


In the case of an attribute the context is the owning classifier.
In the case of an association end the context is the set of types at the other end or ends of the
association.

Tiberiu Leia: Software Engineering Object Oriented Programming

10

Inheritance (motenire)
superclass subclass
subclassing
Ex. class X extends Y
class SubClass extends SuperClass
C++ multiple inheritance
Java simple inheritance only one class
can be inherited

SuperClass
+Attribute1
+Attribute2
+Operation1()
+Operation2()

immediate inherited
SubClass

class hierarchies
+Attribute3
+Attribute4

+Operation1()
+Operation3()
+Operation4()

Tiberiu Leia: Software Engineering Object Oriented Programming

11

UML representation of class


extension relation inheritance

Object
attributes
methods

Class1
attributes
methods

All the hierarchies have Object class as an ancestor


direct or indirect inheritance

Tiberiu Leia: Software Engineering Object Oriented Programming

Attribute - data that


characterize a class.
Attributes are obtained by
abstraction of information
(processed by a point of
view).

Class2
attributes
methods
Class3
attributes
methods
12

Creation of an object instantiation of a class


(instaniere)
Cannot be an object without the corresponding class
Not all the classes have to be instantiated.
How can be used the classes that are not instantiated?

Tiberiu Leia: Software Engineering Object Oriented Programming

13

Class definition
[modifiersList] class ClassName [extends SuperclassName] [implements
interfaceList]
{
ClassBody
}
[] optional.
modifierList keywords: public, abstract, final, etc.

Class Members
Member domain
Tiberiu Leia: Software Engineering Object Oriented Programming

14

Type memberName; //declaration


{
//memberName domain
}
Access modifiers: public, protected and private.

Tiberiu Leia: Software Engineering Object Oriented Programming

15

4. Fields
Class variables and instance variables (variabile de clas)
A variable is an item for data named by an identifier.
Class variables = static variables
They have static modifier.
Example:
static int i=5;//class variable
static Type variableName;
Reference manner:
ClassName.variableName
objectReference.variableName It is not accepted by all compilers for static variables!
Instance Variables (variabile de instan)
Example:
Tiberiu Leia: Software Engineering Object Oriented Programming

16

int i=5;//instance variable


Reference manner:
objectReference.variableName

Tiberiu Leia: Software Engineering Object Oriented Programming

17

Attribute declaration
Attributes are primitive data or reference data (constructed from class or arrays).
[modifiersList] DataType variableDeclarationList;
modifierList contains:

access modifiers (public, protected or private)


final
static
transient and
volatile.

Tiberiu Leia: Software Engineering Object Oriented Programming

18

DataType contains:

primitive data types


any class type
any interface reference type
any array (it is a class type).(tablou - vector)
variableDeclarationList

public int x=10, y, z; //instance variable

Tiberiu Leia: Software Engineering Object Oriented Programming

19

5. Methods
method = function service or behavior
Method declaration
implementation = { //sequence of instructions }
A method has: definition and body
The method definition has:
return type of the variable may be void
name
list of arguments - may be empty.
method signature = returnType+name+parameterList

Tiberiu Leia: Software Engineering Object Oriented Programming

20

Method declaration:
[modifierList] ReturnType methodName([argumentList]) [throws exceptionList]
{
methodBody;
}

Tiberiu Leia: Software Engineering Object Oriented Programming

21

modifierList:

public Accessible for anybody


protected accessible by same package classes and subclasses outside the package
private accessible from the same class
abstract
static
final cannot be modified
synchronized for threads
native native methods (C, C++, FORTRAN or assembly language).

The list of method arguments


variables declarations scope
Tiberiu Leia: Software Engineering Object Oriented Programming

22

In a class can be two or more methods with the same name. They have to differ by:
number of parameters or their type

Tiberiu Leia: Software Engineering Object Oriented Programming

23

Example:
public class ClassName {
static void met1() {
System.out.prinln("Method1");
}
static void met2() {
System.out.println("Method 2");
}
public static void main(String args[]) {
met1();met2();
}
}

Tiberiu Leia: Software Engineering Object Oriented Programming

24

Method overwriting
Method signature
Overwriting a method in a subclass the method from the superclass is concealed in the
subclass by the new implementation
public class SuperClass {
//attributes .
static void met1() {
System.out.prinln("Method1");
}
static void met2() {
System.out.println("Method 2");
}
}

public class SubClass extends SuperClass {


//attributes .
static void met2() {
System.out.prinln("Method2SubClass");
}
static void met3() {
System.out.println("Method 3");
}
}

Tiberiu Leia: Software Engineering Object Oriented Programming

25

objectReference.methodName(); //instance method call


ClassName.methodName();/class method call
int a[]=new int[3]; // object creation
...........................
public void met(int arg[]) {
arg[0]=1;
arg[1]=2;
arg[2]=3;
return; // when return, the arrays elements are changed
}
.................
met(a); // method call
What does a[] contain after the return from the call?

Tiberiu Leia: Software Engineering Object Oriented Programming

26

Class methods with static modifier


and instance methods without static modifier

How can they be called?


ClassName.staticMethod()
objectReference.instanceMethod()
Math Class
(sin, cos, tan, random etc.)
float y=Math.sin(x);

Tiberiu Leia: Software Engineering Object Oriented Programming

27

6. Constructors
A class can have one or more constructors.
A constructor is a kind of specialized method that is called at the object creation. It
initializes some object data or creates some new reference data.
In a class can be more constructors with different numbers of arguments or different types
of arguments.
default constructor it has no arguments

Tiberiu Leia: Software Engineering Object Oriented Programming

28

Constructor declaration
The name must be the same of the class name. It cannot return any value (including void).
[modifierList] ClassName([parameterList]) [throws exceptionList]
modifierList: private, protected, public, abstract, static, final, native, synchronized.
The constructors body can contain as a first line:
this(parameterList)
or
super(parameterList)
Constructor signature
If a class has not any declaration of a constructor, the default constructor is used.

Tiberiu Leia: Software Engineering Object Oriented Programming

29

public class Name extend SuperClassName{


public Name(int nr) { // constructor
super();
}
//Calling constructor from constructor
public Name(int nr, char c) { // constructor
this(nr); // call of the first constructor (SuperClassName)
}
public void methodName {//method
//method body
}
}

Tiberiu Leia: Software Engineering Object Oriented Programming

30

Class Extension
The constructor overwriting.
Initialization:
Primitive type:

boolean

char

byte

short

int

long

float

double

Implicit value

false

null

0L

0.0F

0.0d

Tiberiu Leia: Software Engineering Object Oriented Programming

31

Initializers (iniializatori)
String[] tablou=new String[] {
nume1, nume2, nume3 };
What does perform the following instruction?
System.out.println(tablou[0]);

Tiberiu Leia: Software Engineering Object Oriented Programming

32

7. Domains and visibility


(domeniu i vizibilitate)
Variables and methods domains (scope) and visibility depend on the place where they
were defined.
C language allows global data and global functions. It is not the case of Java.
Domain = scope
A variable scope is the region of a program where the variable can be referred to by its
simple name.
Scope visibility
Visibility determines whether the variable can be used from outside of the class within it is
declared. Visibility is set with an access modifier.
In some part of a program, a variable can be shadowed by other declarations. There, the
variable name is used by another declaration.
Unlike other language, some Java compilers do not accept the construction:
{
Tiberiu Leia: Software Engineering Object Oriented Programming

33

int a=1;
{
int a=2;
a= ;// confusion which a?
}
}

Tiberiu Leia: Software Engineering Object Oriented Programming

34

8. Object Creation and Destruction


(crearea i distrugerrea obiectelor)
Creation
An object (instance) is created dynamically using a class or an array type.
Creation with new operator:
String str = new String();
ClassName objectReference = new ClassName();

Tiberiu Leia: Software Engineering Object Oriented Programming

35

Initialization order when a class is instantiated using a


superclass:
1. initialization of static attributes from the superclass
2. initialization of static attributes of the subclass
3. initialization of instance attributes from the superclass
4. constructor call of the superclass
5. initialization of instance attributes of the subclass
6. call of the subclass constructor

Tiberiu Leia: Software Engineering Object Oriented Programming

36

Example:
System.out.println(str);
System
System.out is an instance of PrintStream.
method println()
Operatorul instanceof
boolean b= referinta instanceof NumeClasa;
b takes true if referinta is an instance of the class NumeClasa.

Tiberiu Leia: Software Engineering Object Oriented Programming

37

Distruction
String s=new String(); //
............................
s=null; //the object is no anymore referred by s
System.gc(); // call the execution immediately of the garbage collector
Execution of an application
public void static main(String[] args) { ... }
The class that implements the method main() is not automatically instantiated.
How can be used non static variable declared outside main method?
What kind of variables can be used in static methods?
Tiberiu Leia: Software Engineering Object Oriented Programming

38

Object Class
Constructor:
public Object()
It is in the package java.lang.

Object Class methods:


public native Object clone() throws CloneNotSupportedException
public boolean equals(Object obj)
protected void finalize() throws Throwable
public final native Class getClass()
public final native void notify()
public final native void notifyAll()
public String toString()
public final void wait() throws InterruptedException
public final void wait(long timeout) throws InterruptedException
public final void wait(long timeout, int nanos) throws InterruptedException

Tiberiu Leia: Software Engineering Object Oriented Programming

39

Example of Program: Complex Numbers


/* Clasa pentru crearea si utilizarea numerelor complexe z=a+ib */
public class Complex {
//Date pentru stocarea informatiilor (starea) numarului complex:
double a,b; //Cum sunt initializate?
//Constructori:
//Constructor implicit suprascris
public Complex() {
a=0;
b=0;
}
//Constructori cu parametrii
public Complex(double x, double y) {
a=x;
b=y;
}
public Complex(Complex c) {
a=c.a;
b=c.b;
}
Tiberiu Leia: Software Engineering Object Oriented Programming

40

//Metoda statica ce aduna doua numere complexe si returneaza rezultatul


public static Complex add2(Complex z1,Complex z2) {
Complex z=new Complex();
z.a=z1.a+z2.a;
z.b=z1.b+z2.b;
return z;
}
//Metode de instanta
public void putAdd(Complex c) {
//aduna parametrul la numarul curent si memoreaza rezultatul
a=a+c.a;
b=b+c.b;
return;
}
public Complex getAdd(Complex c) {
Complex z=new Complex(); //variabila temporara
z.a=a+c.a;
z.b=b+c.b;
return z;
}
Tiberiu Leia: Software Engineering Object Oriented Programming

41

//Subtract methods Completati cu metodele corespunzatoare!


//Multiply methods Completati cu metodele corespunzatoare!
//Divide methods Completati cu metodele corespunzatoare!
//Metoda de conversie a numarului complex intr-un String (a,ib)
// Completati cu metoda corespunzatoare!

public String toString()


{
String s=new String();
s="("+a+",i"+b+")";
return s;
}

//Suprascrie metoda din clasa Object

Tiberiu Leia: Software Engineering Object Oriented Programming

42

/* Clasa de testare a utilizarii numerelor complexe */


public class TestComplexe {
public static void main(String[] args) {
//Instantiaza doua numere complexe
Complex c1=new Complex(2.1,3.2);
Complex c2=new Complex(3.3,4.4);
c1.putAdd(c2);
Complex c3=c1.getAdd(c2);
//Afiseaza rezultatele calculelor
System.out.println("c1="+c1+"; c2="+c2+"; c3="+c3);
}
}

Tiberiu Leia: Software Engineering Object Oriented Programming

43

Problems:
1) Fill the Complex class with others methods.
2) Transform the program in one that works with complex numbers of the type float.
Suggestions:
float x=(float) 3.4;
double y=(double) x;
float z=(float) y;

Tiberiu Leia: Software Engineering Object Oriented Programming

44

Class Diagram

TestComplexe
+main(String[]): void

ClassName
+attribute1
+attribute2: data_type
+attribute3: data_type = i_value
+operation1()
+operation(arg_list): result_type

Complex
+a: double = 0
+b: double = 0
+add2(Complex, Complex): Complex
+putAdd(Complex): void
+getAdd(Complex): Complex
+toString(): String

A Class diagram shows the existence of classes and relationships in a logical view of a system.

Tiberiu Leia: Software Engineering Object Oriented Programming

45

TestComplexe
+main(String[]): void

Class TestComplexe uses class System.


System should be included (import) into
application.

Complex
+a: double = 0
+b: double = 0
+add2(Complex, Complex): Complex
+putAdd(Complex): void
+getAdd(Complex): Complex
+toString(): String

System
+out: PrintStream
+print(String): void
+println(String): void

Tiberiu Leia: Software Engineering Object Oriented Programming

46

9. Inheritance + modifiers
The procedures used to construct classes from other classes are extension, composition or
aggregation.
Inheritance is a procedure to transmit the behavior and attributes of a class to
another one.
The class that inherits has the behavior and the attributes of the inherited class.
Inherited class = superclass,
The class that inherits is subclass.
subclassing . class hierarchy.
The member of a class declared private are not inherited by their subclasses.
The members of a class declared protected or public are inherited by the classes included
into packages that dont contain the superclass.
If a class inherits an abstract method, it has to implement it, or the class must be
declared abstract.
- abstract method = method without implementation
Tiberiu Leia: Software Engineering Object Oriented Programming

47

Example
class Class1
{
int p1=1;
public void met1()
{
System.out.println("Metoda met1()");
}
}

Class1
MainClass

+p1: int = 1
+met1(): void

+main(String[]): void

class Clasa2 extends Class1


{ //Extindere
int p2=2;
public void met2()
{
System.out.println("Metoda met2()");
}
}

Tiberiu Leia: Software Engineering Object Oriented Programming

Class2
+p2: int = 2
+met2(): void

48

public class MainClass


{
public static void main (String[] args)
{
Clasa1 ob1=new Clasa1();//Aggregation
Clasa2 ob2=new Clasa2();//Agreggation
System.out.println("Object ob1 has p1= "+ob1.p1);
System.out.println("Object ob2 has p1="+ob2.p1+"; p2="+ob2.p2);
ob1.met1();
ob2.met1();
ob2.met2();
}
}

Tiberiu Leia: Software Engineering Object Oriented Programming

49

10. Aggregation (agregare)


A program can be also developed by aggregation or composition.
Aggregation = a whole is made of (physically composed of) its
parts.
unidirectional association. There are two kinds of
aggregations.

ClasaA

ClasaB

attributes

attributes

methods

methods

Strong aggregation
(composite
aggregation)

a) Composition = Strong aggregation (compoziie)


The instance of ClassA is responsible of creation of the instance of ClassB. If the instance of
ClassA is deleted, the instance of ClassB is deleted too.

Tiberiu Leia: Software Engineering Object Oriented Programming

50

An object of type ClasaA (representing the whole) is direct responsible for creating its parts of
type ClasaB. BIDIRECTIONAL NAVIGABILITY?
An object of type ClasaA are in association relation with n objects of type ClasaB. n = * ;
or n=1
Some typical examples of multiplicity bounds:
0 Collection must be empty
1 Exactly one instance
5 Exactly 5 instances
* Zero or more instances
0..1 No instances or one instance
1..1 Exactly one instance
0..* Zero or more instances
1..* At least one instance
m..n At least m but no more than n instances
The solid diamond denotes composition. The strong form of aggregation is characterized by the
fact that components cannot exist without the aggregate. They have the same life span.
Tiberiu Leia: Software Engineering Object Oriented Programming

51

Implementation:
Variant 1)
class ClasaA {
ClasaB cb=new ClasaB();
...........................
}
Variant 2)
class ClasaA {
ClasaB cb;
ClasaA() {
cb=new ClasaB();
.....................
}
}
Variant 3)
class ClasaA {
ClasaB cb;
ClasaA(Type x) {
cb=new ClasaB(x);
Tiberiu Leia: Software Engineering Object Oriented Programming

52

.....................
}
}
How can be implemented for n?
How can be implemented BIDIRECTIONAL NAVIGABILITY and how can be tested the
bidirectional navigation?

Tiberiu Leia: Software Engineering Object Oriented Programming

53

b) Light aggregation (Shared aggregation)


ClassA uses ClassB
ClassA not necessarily contains an
instance of ClassB.
If an object of ClassA is not necessarily
the owner of an instance of ClassB, then
the last can be included in different
instances of ClassA.
The instance of ClassA and the instance
of ClassB dont have necessarily the
same life span (time).

Target

ClassA

Source

+1..*

ClassB

Light Aggregation

Tiberiu Leia: Software Engineering Object Oriented Programming

54

public class ClassB {


ClassA parent;
int valB;
String name;
public ClassB(ClassA ref, String nm) {
parent=ref;
name=new String(nm);
}
public void metB() {
System.out.println("metB: this is "+name+" that has valB= "+valB);
System.out.println("metB: parent is "+parent.name+" that has valA= "+parent.valA);
}
}
public class ClassA {
String name;
ClassB child;
int valA;
public ClassA(String nm){
child=new ClassB(this,"ObjectB");
name=nm;
}
public void metA(){
System.out.println("metA: "+name+": valA="+valA);
System.out.println("metA: child= "+child.name+":
valB="+child.valB);
}
}

Tiberiu Leia: Software Engineering Object Oriented Programming

55

MainClass

ClassA

+obA: ClassA

+obB: ClassB
+valA: int

+main(): void

+metA(): void

ClassB
+valB: int
+metB(): void

REZULTS: (CONSOLE OUTPUT)


metB:
metA:
metA:
metB:
metB:
metA:
metA:
metB:
metB:

public class MainClass {


public static void main(String[] args)
{
ClassA obA=new
ClassA("ObjectA");
obA.metA(); obA.child.metB();
obA.valA=2;
obA.child.valB=2;
obA.metA(); obA.child.metB();
obA.child.valB=3;
obA.child.parent.valA=5;
obA.metA(); obA.child.metB();
}
}

parent is ObjectA that has valA= 0


ObjectA: valA=2
child= ObjectB: valB=2
this is ObjectB that has valB= 2
parent is ObjectA that has valA= 2
ObjectA: valA=5
child= ObjectB: valB=3
this is ObjectB that has valB= 3
parent is ObjectA that has valA= 5

Tiberiu Leia: Software Engineering Object Oriented Programming

56

public class ClassB {


ClassA parent;
int valB;
String name;
public ClassB(ClassA ref, String nm) {
parent=ref;
name=new String(nm);
}
public void metB() {
System.out.println("metB: this is "+name+" that has valB= "+valB);
System.out.println("metB: parent is "+parent.name+" that has valA= "+parent.valA);
}
}

MainClass

ClassA

+obA: ClassA

+obB: ClassB
+valA: int

+main(): void

+metA(): void

Tiberiu Leia: Software Engineering Object Oriented Programming

ClassB
+valB: int
+metB(): void

57

public class ClassA {


String name;
ClassB child;
int valA;
public ClassA(String nm){
child=new ClassB(this,"ObjectB");
name=nm;
}
public void metA(){
System.out.println("metA: "+name+": valA="+valA);
System.out.println("metA: child= "+child.name+": valB="+child.valB);
}
}
public class MainClass {
public static void main(String[] args) {
ClassA obA=new ClassA("ObjectA");
obA.metA();
obA.child.metB();
obA.valA=2;
obA.child.valB=2;
obA.metA();
obA.child.metB();
obA.child.valB=3;
obA.child.parent.valA=5;
obA.metA();
obA.child.metB();
}
}

MainClass

ClassA

+obA: ClassA

+obB: ClassB
+valA: int

+main(): void

Tiberiu Leia: Software Engineering Object Oriented Programming

+metA(): void

ClassB
+valB: int
+metB(): void

58

Light (Indirect) aggregation


UNIDIRECTIONAL NAVIGABILITY

ClasaA
attributes
methods

Indirect
Aggregation
ClasaB
attributes
methods

An object of type ClasaA (representing the whole) is not necessarily direct responsible of
creating its part of type ClasaB. The objects dont have the same life span.
An object type ClasaA is in relation with n objects of type ClasaB.
n = * ; or n=1

Tiberiu Leia: Software Engineering Object Oriented Programming

59

Implementation:

How can be implemented for n?

class ClasaC {
......................
static ClasaB metoda(Type par) {
......................................
ClasaB b=new ClasaB(par);
......................................
return b;
}
}

class ClasaA {
ClasaB cb;
...................
ClasaA(Type par) {
cb=ClasaC.metoda(par);
..............................
}
...................
}

Tiberiu Leia: Software Engineering Object Oriented Programming

60

Example:
/* Program*/
public class Class1 {
public static void main(String args[]) {
Class1 ob1=new Class1();// Self instantiation
Class2 ob2=new Class2(); //Instantiation of another class
System.out.println("Intrare main()");
ob1.met1();
ob2.met2();
}
public void met1() {
System.out.println("Mesaj: metoda1");
}
}
class Class2 {
public void met2() {
System.out.println("Mesaj: metoda2");
}
}
Homework: Draw the diagram that describes the relations between classes of the previous
program!
Tiberiu Leia: Software Engineering Object Oriented Programming

61

*
****
***END***
****
*

Tiberiu Leia: Software Engineering Object Oriented Programming

62

You might also like