1
Object Oriented Programming
in Java
Doc. Ing. František Huňka, CSc.
2
Literature, Web Resources
• Barnes D. Kolling M.: Object First with
Java. Pearson fourth edt. 2009
• Eckel, B.: Thinking in Java
3
Curriculum
1. Basic concepts, platforms, UML, class &
instance, Java development, constructors.
2. Classes closer look, primitive & object data
types, this, modifier final, class attributes, class
methods, main method.
3. Composition & aggregation, overloaded
constructors, packages, JAR files, import.
4. Control statements, if, if else, for, while, break,
continue, switch, logical operators
5. Inheritance, information hiding, method
overriding.
4
Curriculum
6. Polymorphism, abstract class, abstract
method, interface
7. Arrays, class Register, Exceptions
8. Collections, basic classes, graphical user
interface (GUI)
5 Benefits of Object-Oriented
Perspective
• There are three main benefits:
–Real world apprehension
– Stability of design
–Reusability (at the programming code
level)
6
Real world apprehension
• Object-orientation is close to our own
natural perception of the real world.
• The basic philosophy underlying object
oriented programming is to make the
programs as far as possible reflect that
part of the reality they are going to
treat.
problem
specific
concepts
realized
concepts
(classes)
phenomena objects
(instances)
abstraction abstraction
referent system model system
7
Programming process as a modeling process
modeling
8
Components of modeling process
• A phenomenon is a thing that has
definite, individual existence in reality
or in the mind; anything real in itself.
• A concept is a generalized idea of a
collection of phenomena, based on
knowledge of common properties of
instances (objects) in the collection.
9
Stability of design
• Instead of focusing on the functionality of a system, the first step in the system’s development is to make a physical model of the real world with which the system is concerned.
• This model then forms the basis for the different functions that the system may have.
• Functions may later be changed, and new functions may be added without changing the underlying model.
10
Reusability – traditional approach
• One well known problem with software development is
being able to reuse existing software components when
developing new ones.
• The new component is often implemented by copying
and modifying the existing component, but this means
that it must be tested again.
• More problems, however, is that the relations between
the old and new components may be lost; if an error is
detected in one, it must be corrected in both. Also
changes to common parts of the system may have to be
performed in both components.
11
Reusability – object oriented approach
• Object-oriented programming languages
have strong constructs for supporting
incremental programming modification.
• It is possible to define a new component as
an incremental extension of an existing one,
thus preserving the relations between the
two components.
• Most object oriented languages are based on
the class/subclass mechanism (inheritance).
12
Reusability - disadvantages
• The disadvantage of incremental
modification is that the library of
components reflects the historical
development of the components.
• In addition, the relations between
components are mainly dictated by
maximal code sharing, often
conflicting with the modeling
requirements.
13 Fundamental means of organization for
apprehending the real world
• Identification of phenomena and their properties. The result of this is a number of singular phenomena characterized by a selected set of properties. The phenomena are singular since they have not been classified in terms of concepts.
• Classification is the means by which we form and distinguish between different classes of phenomena. That is we form concepts. Having identified phenomena and their properties and concepts, we group similar phenomena and concepts.
14 Fundamental means of organization for
apprehending the real world
• Classification is often called a taxonomy.
When classification is applied repeatedly,
classification hierarchy may be obtained.
• Composition. A phenomena may be
understood as a composition of other
phenomena. There are two basic types of
composition: whole part composition and
aggregation (reference composition).
15
Object oriented languages
• Simula – dated back to 1967
• Smalltalk – introduced model-view-control
mechanism
• C++
• Beta
• Self, Ada
• Java
16
Java as a Technology
• Object oriented
• Platform independent
• Robust, dynamic and safe
• Multiprocess
• Support Component Software Development
• Distributed
Outline 17
Program structure in
Java
Compilation
Execution
(Interpretation)
public class HelloWord {
public static void main(String args[])
{ //metoda main začíná provádění Java aplikace
System.out.println( “Hello World” );
} // konec metody main
} // konec třídy HelloWorld
javac HelloWorld.java - compilation
java HelloWorld – interpret runs method main from the HelloWorld class
Outline 18
Java Object
Application
public class Hello { private String greeting = “Hello World!”
//Method that does the work
public String getGreeting() {
return greeting;
}
public void go() {
System.out.println(getGreeting());
}
}
public class HelloTest { public static void main(String args[]) {
Hello hi = new Hello();
hi.go();
Hello hello1 = new Hello();
hello1.go();
}
}
Poznámky
19
Class Dog
public class Dog { private String breed; private int age; private String color; public void barking() { System.out.println("Low level of barking"); } public void hungry() { System.out.println("The dog is fed up"); } public void sleeping() { System.out.println("The dog is watching"); } //access and modification methods public String getBreed() { return breed; } public int getAge() { return age; } public String getColor() { return color; }
Poznámky
20
Class Dog
public void setBreed(String newBreed) { breed = newBreed; } public void setAge(int age) { this.age = age; } public void setColor(String color){ this.color = color; } }
Poznámky
21
Class DogTest
public class DogTest { public static void main(String[] args) { Dog dog1 = new Dog(); Dog dog2 = new Dog(); dog1.barking(); dog2. sleeping(); dog1.print(); } }
20
Platform Independent
• Java Bytecode (files .class) is a
compilation product of the source files, which
is independent of computer architecture
– Libraries java.awt.*, java.net.*, java.applet.*
• Java Virtual Machine (JVM) – imaginative machine implemented by means of
program emulation on real machine
– Instruction packet, registers, stack, garbage collector
21
Typical Development Environment in Javě
Editor
Compiler
Class Loader
Bytecode Verifier
Java Virtual Machine
Disk
Disk
Disk
Primary Memory
Phase 1: Edit
Phase 2: Compile
Phase 4: Verify
Phase 3: Load
Phase 5: Execute
Primary Memory
Primary Memory
Program created and stored in .java file
Compiler creates bytecode, which is stored into .class file
Class loader reads .class file from disk
and stores it into the memory
Bytecode verifier validates the whole bytecode
JVM reads bytecode and translates it into machine code (interprets bytecode)
22
Sun Microsystem – 2 Basic Products
• J2SE Runtime Environment (JRE) that provides:
– libraries, Java virtual machine, and further
components that are necessary for applet execution
and application execution written in the Java
language.
• J2SE Development Kid (JDK) covers:
– JRE plus row oriented development tools such as
compilers, debugging programs, which are necessary
for application and applet development.
23
Java Programming Language
• Java is generally usable, concurrent, strongly typed, object oriented language based on classes. Java language is normally compiled into byte-code sets of instructions and binary format defined in Java Virtual Machine specification.
• Java virtual machine (JVM) is an abstract computer machine, which has a set of instructions and manipulates memory during the execution of the program. JVM is ported on different platforms and provides both hardware and operating system independence.
24
What is UML 1/2
• Unified Modeling Language – (UML) a
standard language for specification,
vizualization, creation, and dokumentation of
the programing systems, in the same way also
for business modeling and different not
programming systems.
• UML is most spread graphical representation
chart for object oriented systems modeling.
25
What is UML 2/2
• UML represents a collection of the best
engineering experience, which were
successfully proven in huge and complex
systems modeling.
• UML mainly exploits graphical notation for
expressing of the software project design.
• Using UML helps project teams to
communicate, examine potential design and
check the software systems architecture design.
26
Objectives of UML 1/2
1. Provide users with simple, expressive visual
modeling language in order they could develop and
change thoughtful models.
2. Provide mechanism for extension and further
specification of the basic concepts.
3. Be independent on concrete programming language
and created processes.
4. Provide a formal foundation for understanding
modeling language.
27
Objectives of UML 2/2
5. Support high level development concepts
such as cooperation, programming
frameworks, patterns and components.
6. Integrate the best experience.
28
UML Diagrams Types1/2
• Each UML diagram is designed to allow
developers and customers to have a view of
software system from different perspectives and
changing levels of abstraction. UML diagrams
generally create visual model tools that include:
29
UML Diagrams Types
• Use Case Diagram
• Class Diagram
• Interaction Diagrams
– Sequential Diagram
– Cooperation Diagram
• State Diagram
• Activity Diagram
• Physical Diagrams
– Component Diagram
– Deployment Diagram
30
Class Diagram 1/2
• Class diagram models structure and contents of
the classes, for which it uses designed elements
such as – classes, packets and objects. This
diagram displays association between classes.
Further specification of association can be
composition, inheritance and so on.
31
Class Diagram 2/2
1 *
Class name
Attributes
Operations, methods
association
cardinality
Customer
-name
-address
-listOfOccupations
+print()
+bestPaidOccupation()
+monthlyPaiments()
Order
-dateOfAcceptance
-isPaid
-number
-price
+print()
+send()
+wholePrice()
Customer
-name
-address
-listOfOccupations
+print()
+bestPaidOccupation()
+monthlyPaiments()
32
Class Point
• data attributes (data members)
– x, y coordinates
• methods
– move
– toString (inherited from class Object) – create text
representation of the object
Outline 33
Class Point
public class Point
{
private
private
int x;
int y;
public void move(int dx, int dy) {
x = x + dx; y = y + dy;
}
public String toString() {
String t = "X: "+ x +" Y: "+y;
return t;
}
public void print() {
System.out.println(“Point coordinates: "+this.toString());
}
}
Outline 34
Class PointTest
a – receiver
print() – message
without parameters
move(20 , 30) –
message with
parameters
public class PointTest
{
public static void main(String[] args)
{
Point a = new Point( );
System.out.print(“Point
a.print();
a.move(20 , 50);
System.out.print(“Point
Point b;
a: “);
a: “);
a.print( );
b = a;
b.print( );
System.out.print(“Point
b.move(-100, -200);
System.out.print(“Point
a.print();
b: “);
a: “);
}
}
Point a: Point coordinates: X: 0 Y: 0
X: 20 Y: 50 Point a: Point coordinates:
Point b: Point coordinates: X: 20 Y: 50
Point a: Point coordinates: X: -80 Y: -150
35
Graphical Representation
a
b null
x 0
y 0
36
Message
• Message that are sent to objects are
typically composed of receiver of the
message, message selector (message name)
and possible message parameters:
System.out.println(“Printed text … “ + variable);
receiver method parameters
37
Object encapsulation
data attributes
method1
method2
method3
Object
message
38
Object oriented notation
receiver.message(possible parameters);
resultObj = receiver.message(possible
parameters);
39
Access and Modification Methods
• access methods:
– start with get (conventions)
– getX() returns x coordinate
• modification methods:
– start with set (conventions)
– setX(type new argument)
– setX(int newValue) sets x to the new value
Outline 40
public class Point
{
private int x;
private int y;
public void print() {
System.out.println(“Point coordinates: "+this.toString());
}
public int getX() {
return x;
}
public void setX(int x){
this.x = x; }
public String
String t
toString() {
= "X: "+ getX() +" Y: “ + getY();
return t;
}
public void move(int dx, int
setX( dx + getX()); // x
setY( getY() + dy); // y
}
dy) {
= x + dx;
= y + dy;
}
41
Object Technology
• In the object model of computation we work only
with two possible operations with the objects. The
first of them is name an object – when an object is
assigned to the variable, by which it is accessible.
• The second operation is so called sending a
message. Message represents a request for
operation execution (method) of the given object.
A message can also contained parameters that
represent so called forward data flow (in the
message propagation direction) in the direction to
the message receiver.
42
Object Technology
• The result of sent message is execution of the code
of one of the object’s methods, which accepted the
message. The code of the executed method usually
gives some result, which represents reverse data
flow (in the direction from receiver of the message
to the sender of the message).
• Regarding to the possibility of code the results of
the executed methods are not restricted only to
single object attributes but it can be the whole
objects.
43
Object Technology
• Running object oriented program is created
by a system of mutually communicating
objects, which is managed primarily by a
sequence of external events from interface
of the program.
• Main program can be e.g. created by only
single object declaration and sending a
message to the object.
44
Encapsulation
• Advantage of encapsulation:
– Programs can be tested by smaller parts
– Encapsulation helps to get rid of a frequent mistake
connected with shared access to the common data.
– Internal data strukture can be changed without necessity
to change object environment (change of the data
attribute names)
– Libraries of objects can be created by abstraction of the
data types and it will be possible to reuse them in other
applications.
45
Encapsulation
– Data the program works with are protected and
identified. So data protection and data identification is
assured.
– Encapsulation helps to separate interface –
(visible part of object) from implementation
(hidden part of object).
46
Encapsulation
• From the object definition results that the object typically put together data and operation over the data in one inseparable whole with data protection. Data used to be connected with theit operations so tightly thast it is impossible to access them without their operations.
• Self-identification – object itself knows what it is, so the memory containing objects contains information of the object’s structure too.
47 Information Hiding
External - Internal
• Speaking about external information hiding
we have into our mind that objects should
not either access their local data directly nor
the code of individual operations. Object
should be seen as an entity that is
impossible to see through.
48 Information Hiding
External - Internal
• Speaking about internal information hiding
we have into our mind the fact that in the
scope of inheritance the successors do not
have access to the local data attributes of
their ancestors as well as to the code of
individual operations of their ancestors.
• Object can be understood as dynamic
entities, which emerge, create new objects
and decline during the running of the
application.
49
Allocation Memory Management
• Problem of terminated objects is usually
solved by a special program called garbage
collector (clear the memory from declined
objects).
• Objects with no reference to them.
50
Initializing objects with constructors
• Java requires a constructor call for each
object that is created, which helps ensure
that the object is initialized properly before
it is used in a program – the constructor call
occurs implicitly when the object is created.
• In any class that does not explicitly include
a constructor, the compiler provides a
default constructor – that is, a constructor
with no parameters.
51
Constructors
• The constructor name is always identical
with the class name whose objects it
creates.
• There are no return values with
constructors.
• In case defining more constructors they
must differ number or type of parameters.
52
Constructors with Point Class
• declaring one constructors we must declare
all other types of constructors
• we speak about constructor’s overloading –
more constructors that differ in number or
type of parameters
Outline 53
Class Point 1/2
public class Point
{
private int x;
private int y;
// Constructor
public Point()
// initialise
x = 0; y=0;
}
without parameters
{
instance variables
// constructor with
public Point(int c)
x = c; y = c;
}
// constructor with
public Point(int x,
this.x = x; y =
}
one parameter
{
two parameters
int newY) {
newY;
public String toString()
{
String t = "\nX: "+ getX() + "
return t;
}
Y: “ + getY();
Outline 54
Class Point 2/2
public void print()
{
System.out.println(“Point
}
coordinates:
"+this.toString());
public int getX()
{ return x; }
public int
getY(){
return y; }
public void setX(int
x){ this.x = x;
}
public void setY(int
y){ this.y = y;
}
public void setPoint(Point
x = a.x;
y = a.y;
}
a){ //copy constructor
public Point getPoint(){
return this;
} }
Outline 55
Class PointTest
public class PointTest
{
public static void main(String[] args){
Point a, b, c; String t;
a = new Point();
b = new Point(-10, 122);
c = b.getPoint();
c.tisk();
if (b==c) t = “Yes identical"; else t = “No different”;
System.out.println(“Comparison result
c.setPoint(a); // copy constructor
a.print();
b.print();
c.print();
of two objects: "+t);
}
}
56
Point with Name Attribute
• to distinguish among different object we
add next attribute with name
• name – String
• change:
– add new constructor
– method toString()
– add access and modification methods for the
new attribute
Outline 57
Class PointName 1/2
public class PointName
{
private
private
private
int x;
int y;
String name;
public PointName() {
x = 0; y=0; name=“not assigned";
}
public PointName(int c)
{
x = c; y = c; name=“not
}
assigned";
public PointName(int x, int
{
this.x = x; this.y = y;
}
public PointName(int x, int
{
this.x = x; this.y = y;
}
y)
name= “not assigned";
y, String jm)
name= jm;
public String toString()
{
String t = "\nName of Point: "+getName() + " X: “ +
getX() +" Y: "+getY();
return t;
}
Outline 58
Class PointName 2/2
public void print()
{
System.out.println(this.toString());
}
public int getX() {
return x; }
public void setX(int x) {
this.x = x;
}
public String getName(){
return name;
}
public void setName(String
name = newName;
}
public void move(int dx, int dy)
{ setX(getX() + dx);
setY(getY() + dy; }
}
newName){
Outline 59
Class PointNameTest
public class PointNameTest
{
public static
{
void main(String[] args)
PointName
PointName
PointName
PointName
PointName e;
a = new PointName();
b = new PointName(12);
c = new PointName(100, 200);
d = new PointName(10, 20, "DDD");
a.print(); b.print(); c.print(); d.print();
e = d;
e.move(100, 200);
d.print(); e.print();
}
}