EEI4362 – Object Oriented
Programming Concepts and
Multi-threaded
Programming
Day School 1
Centre for IT Education Services (CITES)
1
The Open University of Sri Lanka
Outline of Syllabus
Day School 1
• Unit 1: Programming Concepts
Session 1: Object Orient program development
Session 2: Multi-threaded programming
• Unit 2: Application of Object Oriented Concepts
Session 3: Interfaces and abstract classes
Session 4: Application of fundamental concepts
Session 5: Best practices in class design and coding
2
Outline of Syllabus
Day School 2
• Unit 3: Object-oriented Analysis and Design
Session 6: UML and UML notations
Session 7: Requirement Analysis - Use cases
Session 8: Requirement Analysis - Activity and state transition
Session 9: Class and object diagrams
Session 10: Sequence diagrams
Session 11: Collaboration diagrams
Session 12: Packaging or component diagrams
3
Outline of Syllabus
Day School 3
• Unit 4: Design Patterns and Frameworks
Session 13: Basics of Design Patterns
Session 14: Creational Patterns
Session 15: Behavioral Patterns
Session 16: Structural Patterns
Session 17: Best practices and industry frameworks
• Unit 5: Application Development
Session 18: Introduction to application development[Use of Design patterns(MVC) ]
Session 19: Front end development(JSF, JSP, JQuery)
Session 20:Database Connectivity Object Relational Mapping(Hibernate)]
4
Practical Sessions ( 4 PS)
1. Write simple java programs to get familiar with Java
control structures, class and method declarations,
refactoring techniques.
Write simple java programs to illustrate applying OOP concepts
2. Use of API, Interfaces and abstract classes
3. Write a Multithreaded programming
4. Using Hibernate, Object Relational Mapping, use of
Factory and Abstract factory design pattern
5
Overall Continuous Assessments
• Tutor Marks Assignments (TMA) -TMA 1 , TMA 2
• Continuous Assessment Test (CAT) - CAT 1, CAT 2
• Lab Test (LABT) - 4LAB Tests
Eligibility criteria:
• X=AVG(TMA) * 0.3 + BCAT * 0.3 + AVG(LAB) * 0.4 ; If AVG(LAB) > 40
• X = 0; If AVG(LAB) < 40
6
Recommended Reading
Book
• Eck, D.J., 2007. Introduction to programming using Java:
version 5.0, December 2006 : (version 5.0.2, November
2007). Hobart and William Smith Colleges, Department of
mathematics and computer science, Geneva (NY).
7
Object Oriented Programming
8
Object Oriented Programming
• Object Orientation is based on real world.
• Programming model which is based upon the concept of
objects,
• It is an important approach in programming and program
design.
Fundamentals of
OOP? . . .
There are four main fundamentals of Object Oriented Programming
1. Encapsulation
2. Inheritance
3. Polymorphism
4. Abstraction
2
OOP
Inheritance
• A class can extend another class, inheriting all its data
members and methods while redefining some of them
and/or adding its own.
• Inheritance represents the is a relationship between
entities.
For example: a FemaleDancer is a Dancer.
Inheritance
subclass
extends
derived class
public class FemaleDancer extends Dancer
{
...
}
Polymorphism
• Polymorphism is the ability of an object to take on many forms. In
programming languages polymorphism is the capability of an action
or method to do different things based on the object that it is acting upon.
• In Java, we use method overloading and method overriding to achieve
polymorphism.
Activity 1
• Write down the differences between Method overloading
and Method overriding
15
Method Overloading
• When methods have the same name, but different parameters, it is known as method
overloading.
• This can be very useful when you need the same method functionality for different
types of parameters.
Example
public class OverLoadingExample{
public void add(int i, int j){
int k = i + j;
}
public void add(String s, String t){
int k = [Link](s) + [Link](t);
}
}
Method Overriding
If a subclass can define a behaviour that's specific to the subclass type, meaning that a
subclass can implement a parent class method based on its requirement, this feature is
known as method overriding.
Example
public class BaseClass{
public void methodToOverride(){
//Some code here
}
public class DerivedClass extends BaseClass{
public void methodToOverride(){
//Some new code here
} }
Encapsulation
• Encapsulation ensures that data are hidden from users.
• The variables of a class are only accessible through the methods of that
class, making them hidden from other classes. This concept is known as
data hiding.
• To achieve encapsulation in Java,
o declare the class variables as private
o provide public setter and getter methods.
• The setter methods allow modification of the variables' values, while the
getter methods allow viewing of the variables' values.
Encapsulation
public class Vehicle {
private String color;
// Getter
public String getColor() {
return color;
}
// Setter
public void setColor(String c) {
[Link] = c;
}
}
19
Abstraction
• Abstraction means ignoring irrelevant features, properties,
or functions and emphasizing the relevant ones...
“Relevant” to what?
... relevant to the given project (with an eye to future
reuse in similar projects).
Abstraction
• Abstraction is the act of representing essential features without giving
background details or explanations (Hiding the implementation).
• There are two ways to achieve abstraction
1. Abstract classes
2. Interfaces
Dancer
MaleDancer FemaleDancer
21
Abstract
class
•An abstract class cannot be instantiated. That is no objects could be
created for abstract classes.
•Syntax for defining abstract class.
abstract class identifier
{
•Abstract classes can be used as the super classes of inheritance.
•They may OR may not contain abstract methods.
22
Abstract
method
•Abstract method is declared without a method body.
•Syntax for defining abstract class.
Abstract <return_type> <method_name> (<parameter list) ;
•The subclasses (Which are not abstract) of the abstract class should
implement all the abstract methods defined in the parent class.
23
Abstract class
(Cont)
NOTE:
…
• If a class is defined as ‘abstract’, it may or may not contain any abstract
methods.
• If a class does not contain any abstract method, then it can be defined as
abstract only if the programmer needs to restrict the creation of objects
of that class.
• If a class is not abstract, then it cannot hold any abstract method.
24
Abstract Class
Example
The deposit() method is same for both SavingsAccount and KidsAccount.
But for the withdraw() method there are some restrictions for the KidsAccount. Assume that a kid
can withdraw maximum of 500.00 rupees in one transaction.
25
Abstract Class
Example(Cont)
abstract class Account
{
protected String accNo;
protected String name; protected
double balance;
public void deposit(double
amount)
{
balance+=amount;
}
public abstract void
withdraw(double amount);
public void display()
{
[Link]([Link] + "
"+[Link] ); 26
}
Abstract Class
Example (Cont) Withdraw method of Kids Account
Withdraw method of Savings Account
public void withdraw(double amount)
public void withdraw(double
amount) {
{
if(amount<balance) if(amount<balance)
balance-=amount; {
else
[Link]("Erro if(amount<=500)
r:"); balance-=amount;
}
else
[Link]("Amount greater than
500.00");
}else
[Link]("Error:");
}
27
Interface
s
• An interface is a named collection of method definitions (without
implementations).
• There are no attributes defined in the interfaces. If the attributes are
defined, they are implicitly ‘static’ and ‘final’.
• An interface can include constant declarations.
public interface NameOfInterface E.g. :
{ public interface Animal
//Any number of final, static fields {
//Any number of abstract method public void eat();
declarations public void travel();
} }
28
Interfaces
(Cont)
• If the interfaces inherit with classes, the sub classes should
implement all the methods defined in the interface.
• A class can implements any number of interfaces.
class identifier implements <interface1>, <interface2>, <interface3> …
{
//method implementations
}
29
Interfaces
(Cont)
When overriding methods defined in interfaces ,
• The signature of the interface method and the same return type or subtype
should be maintained when overriding the methods.
• An implementation class itself can be abstract and if so interface methods
need not be implemented.
30
Interfaces (Cont)
When implementing interfaces ,
A class can implement more than one interface at a time.
Aclass can extend only one class, but implement many
interfaces.
An interface can extend another interface, similarly to the way that a class can
extend another class. An interface can extend more than one parent interface.
E.g. public interface Hockey extends Sports, Event
31
Interfaces (Cont) …
The interfaces could be used to facilitate multiple inheritance with java.
Interface Class Interface
B C D
s
extend
A
32
Interfaces
Example(Cont)
interface Payable {
}
double getPaymentAmount();
class Invoice implements Payable
{
private String partNumber,partDescription;
private int quantity;
private double pricePerItem;
public Invoice (String part, String
description, int count, double price)
{
partNumber=part;
partDescription=description;
quantity=count;
pricePerItem=price;
}
public double getPaymentAmount()
{
return quantity*pricePerItem;
}
34
}
Interfaces
Example(Cont)
class Employee implements Payable
{
private String empNo,name;
private double basicSalary,otHourPay;
private float otHours;
public Employee( String empNo, String name, double basicSalary, float otHours,
double otHourPay)
{
[Link]=empNo; [Link]=name;
[Link]=basicSalary;
[Link]=otHours; [Link]=otHourPay;
}
public double getPaymentAmount()
{
return basicSalary+otHours*otHourPay;
}
}
34
Next Topic......
Multi-threaded
programming
35
Multitasking and
Multithreading
Multitasking:
• refers to a computer's ability to perform multiple jobs concurrently
• more than one program are running concurrently
Multithreading:
• A thread is a single sequence of execution within a program
• refers to multiple threads of control within a single program
• each program can run multiple threads of control within it
36
Thread
• Java is a multi-threaded programming language which
means we can develop multi-threaded program using
Java.
• A multi-threaded program contains two or more parts that
can run concurrently and each part can handle a different
task at the same time making optimal use of the available
resources specially when your computer has multiple
CPUs.
37
Thread
38
Life Cycle of a Thread
39
Life Cycle of a Thread
• New − A new thread begins its life cycle in the new state. It remains in this state until
the program starts the thread. It is also referred to as a born thread.
• Runnable − After a newly born thread is started, the thread becomes runnable. A
thread in this state is considered to be executing its task.
• Waiting − Sometimes, a thread transitions to the waiting state while the thread
waits for another thread to perform a task. A thread transitions back to the runnable
state only when another thread signals the waiting thread to continue executing.
• Timed Waiting − A runnable thread can enter the timed waiting state for a specified
interval of time. A thread in this state transitions back to the runnable state when
that time interval expires or when the event it is waiting for occurs.
• Terminated (Dead) − A runnable thread enters the terminated state when it
completes its task or otherwise terminates.
40
Creating Threads
• There are two ways to create our own Thread object
1. Subclassing the Thread class and instantiating a new object of that
class
2. Implementing the Runnable interface
• In both cases the run() method should be implemented
41
Create a Thread by Extending a Thread Class
• This approach provides more flexibility in handling multiple
threads created using available methods in Thread class.
Step 1
Override run( ) method available in Thread class. This method provides an entry point
for the thread and you will put your complete business logic inside this method.
public void run( )
Step 2
Once Thread object is created, you can start it by calling start() method, which executes
a call to run( ) method.
void start( );
42
Java Thread Example by extending Thread class
class Multi extends Thread{
public void run(){
[Link]("thread is running...");
}
public static void main(String args[]){
Multi t1=new Multi();
[Link]();
}
}
43
Create a Thread by Implementing
Runnable Interface
• If your class is intended to be executed as a thread then
you can achieve this by implementing a Runnable
interface.
Step1:
you need to implement a run() method provided by a
Runnable interface.
public void run()
44
Create a Thread by Implementing
Runnable Interface
Step 2:
instantiate a Thread object using the following constructor
Thread(Runnable threadObj);
Step 3:
Once a Thread object is created, you can start it by calling
start() method, which executes a call to run( ) method.
void start();
45
Java Thread Example by implementing Runnable
interface
class Multithread2 implements Runnable{
public void run(){
[Link]("thread is running...");
}
public static void main(String args[]){
Multithread2 m1=new Multithread2();
Thread t1 =new Thread(m1);
// Using the constructor Thread(Runnable r)
[Link]();
}
}
46
Using Java Threads
• Most important method: run()
• The default version of this method does nothing so it must
be overridden.
• Should call start() to begin execution of the new thread
• If you are not overriding any of Thread’s other methods,
can simply implement runnable.
47
Thread Methods
void start()
• Creates a new thread and makes it runnable
• This method can be called only once
void run()
• The new thread begins its life inside this method
void stop() (deprecated)
• The thread is being terminated
48
Thread Methods
void yield()
• Causes the currently executing thread object to temporarily pause
and allow other threads to execute
• Allow only threads of the same priority to run
void sleep(int m) or sleep(int m, int n)
• The thread sleeps for m milliseconds, plus n nanoseconds
49
Thread handling with sleep
method
• When a Java program starts up, main thread runs immediately.
• Pausing Execution with Sleep
• Milliseconds [Link] (1000);
• Nanoseconds [Link](0, 100);
• Sleep times are not guaranteed, because they are limited by the
facilities provided by the OS
50
Thread handling with sleep
method
class ThreadSleep extends Thread{
public void run(){
for(int i=1;i<5;i++){
// the thread will sleep for the 500 milli seconds
try{
[Link](500);
}
catch(InterruptedException e)
{[Link](e);}
[Link](i);
}
}
public static void main(String args[]){
ThreadSleep t1=new ThreadSleep();
ThreadSleep t2=new ThreadSleep();
[Link]();
[Link]();
}
51
}
Thread Scheduling
• Execution of multiple threads on a single CPU in some order
is called scheduling
• The JRE uses fixed-priority scheduling which schedules
threads on the basis of their priority
• Thread priorities in the range Thread.MIN_PRIORITY and
Thread.MAX_PRIORITY
52
Thread Scheduling
• The chosen thread runs until one of the following
conditions is true:
• A higher-priority thread becomes runnable.
• The thread yields, or its run method exits.
• On systems that support time-slicing, the thread's time has
expired.
53
-END-
54