Object Oriented Programming
Lab 11
Content
• Interfaces
– What are interfaces
– Ordered
– Derived
– Comparable
• Inner classes
– Static Inner Classes
– Public Inner Classes
– Nested Inner Classes
– Inheriting Inner Classes
– Anonymous Classes
• Threads and Multithreading
– Threads in Java
– Thread Lifecycle
– Synchronization
– Thread Priorities
2
Interfaces
• What is an Interface?
– An interface is a collection of “abstract” methods.
– An interface is a template that a class must adhere to.
– A class implements an interface, thereby inheriting the abstract methods
of the interface.
• Unless the class that implements the interface is abstract, all the
methods of the interface need to be defined in the class.
• The syntax for defining an interface is similar to that of defining a
class
– Except the word interface is used in place of class
3
Interfaces
• An interface is similar to a class in the following ways:
– An interface can contain any number of methods.
– An interface is written in a file with a .java extension, with the name of
the interface matching the name of the file.
– The byte code of an interface appears in a .class file.
4
Interfaces
• An interface is different from a class in several ways:
– You cannot instantiate an interface.
– An interface does not contain any constructors.
– All of the methods in an interface are abstract.
– An interface cannot contain instance variables. The only fields that can
appear in an interface must be declared both static and final.
– An interface is not extended by a class; it is implemented by a class.
– An interface can extend multiple interfaces.
5
Interfaces
• An interface and all of its method headings should be declared public
– They cannot be given private, protected, or package access
• When a class implements an interface, it must make all the methods in the
interface public
• Because an interface is a type, a method may be written with a parameter of
an interface type
– That parameter will accept as an argument any class that implements the interface.
6
Interfaces
• How do I define an Interface…
□ Keyword interface
public interface InterfaceName{
□ Methods are not defined.
public returnType method1(); Note you do not use the
public returnType method2(); keyword abstract
□ The interface is implem
public returnType method3(); ented by a class
}
public class SomeClass implements InterfaceName{
//implement all the methods
} □ It is possible for this class
to be abstract.
7
The Ordered Interface
8
Interfaces
• To implement an interface, a concrete class must do two things:
1. It must include the phrase implements Interface_Name at the start of the
class definition
• If more than one interface is implemented, each is listed, separated by commas
2. The class must implement all the method headings listed in the definition(s) of the
interface(s)
public class SomeClass implements Ordered, Comparable{
□ Multiple interfaces may be implemented
9
The Ordered Interface
10
Interfaces
• An abstract class may implement an interface, However:
1. It is not imperative that all methods be implemented.
2. Unimplemented methods must be marked as abstract;
11
Derived Interfaces
• Like classes, an interface may be derived from a base
interface
– This is called extending the interface
– The derived interface must include the phrase
• extends BaseInterfaceName
• A concrete class that implements a derived interface
must have definitions for any methods in the derived
interface as well as any methods in the base interface
12
Derived Interfaces
13
Comparable interface
• Can be used to provide a single sorting method.
• The Comparableinterface is in the java.lang package, and so is
automatically available to any program
• It has only the following method heading that must be implemented:
public int compareTo(Object other);
□ compareTo allows you to compare objects of
the same type based on any criteria you deci
de.
14
Comparable interface
• int compareTo(Object other);
Must return
– A negative number if the calling object "comes before" the parameter
other
– A zero if the calling object "equals" the parameter other
– A positive number if the calling object "comes after" the parameter
other
• If the parameter other is not of the same type as the class being defined,
then a ClassCastException should be thrown
-1 this < parameter
0 this = parameter
1 this > parameter
15
Writing Comparable
• The following shows an example of the compareTo method
public int compareTo(Object obj){
if (obj == null) throw new NullPointerException(“Object is null”);
if (!this.getClass().equals(obj.getClass())) throw new
ClassCastException("Object not of the same type");
Employee toCompare = (Employee) obj;
if (this.salary > toCompare.salary) return -1;
if (this.salary == toCompare.salary) return 0;
else return 1;
}
16
Using Comparable
• Sort
• Arrays class in java contain a static sort() method that can be
used to sort arrays.
• To sort an array it must contain only Comparable objects.
• To be able to sort objects I must be able to compare them to each other.
• We know we can compare objects if they conform to the interface
Comparable.
17
Comparable interface
18
Comparable interface
□ return this.quantity - compareQuantity
--------- Output ---------
Fruits 1 : Pineapple, Quantity : 70
Fruits 2 : Orange, Quantity : 80
Fruits 3 : Banana, Quantity : 90
Fruits 4 : Apple, Quantity : 100
□ return compareQuantity - this.quantity
--------- Output ---------
Fruits 1 : Apple, Quantity : 100
Fruits 2 : Banana, Quantity : 90
Fruits 3 : Orange, Quantity : 80
Fruits 4 : Pineapple, Quantity : 70
19
Comparable interface
20
Constants in Interfaces
• Java allows for defining constants in interface
• To define a constant it must be marked using
– public static final
• When a class implements the interface it automatically gets the
constants that are declared.
21
Inconsistencies in Interfaces
• Two form of inconsistencies may arise with interfaces
– Inconsistent constants
– Inconsistent methods
• If a class implements two interfaces with the same constant
defined but different values.
• If a class implements two interfaces with the same method
header defined. {return type may be different}
22
Self-Test
• 프로젝트 명: Project11_1
– git commit –m “Project11_1”
• 제공된 InterfaceSelfTest를 사용하여 진행한다.
• 위 프로젝트에서 추가/수정이 필요한 부분은 아래와 같다.
– MyInterfaces interface를 구현(implements)한 MyCustom Class는 추상(abstract) 클래스가
아니다. 따라서, 모든 메소드가 아래 조건에 맞게 구현되어야 한다.
• public void move(String key) 메소드는 key의 값에 따라 move_type은 다음 값을 갖는다.
– w:1/s:2/a:3/d:4/그외:5
• public void attack(String key) 메소드는 key의 값에 따라 isAttack은 다음 값을 갖는다.
– spacebar : (Boolean)true / 그 외 : (Boolean)false
• public void sortItem(Item[] itemList) 메소드는 호출되면 itemList를 정렬한다.
Arrays를 사용하여 정렬하도록 구현한다.
– move_type 변수와 isAttack을 반환하는 public 메소드인 getMoveType()과 getIsAttack()을
구현한다.
– Item Class에 compareTo를 작성한다.
(quantity를 기준으로 오름차순 정렬이 되야 한다.)
23
Self-Test
• 프로그램이 정상적으로 동작한다면 아래의 결과가 Console에 표시된다.
Move Type : 0
Attack : false
ItemList : 5
----------------------------------
Move Type : 2
Attack : true
ItemList
Item[0] : HP (50)
Item[1] : MP (30)
Item[2] : Food (100)
Item[3] : Key (10)
Item[4] : Gold (1)
----------------------------------
ItemList
Item[0] : Gold (1)
Item[1] : Key (10)
Item[2] : MP (30)
Item[3] : HP (50)
Item[4] : Food (100)
----------------------------------
24
Inner Classes
• Inner Classes are classes defined within other classes
• The class that includes the inner class is called the outer class
• An inner class definition is a member of the outer class in the
same way that the instance variables and methods of the outer
class are members
– An inner class is local to the outer class definition
• Using an inner class as a helping class is one of the most useful
applications of inner classes
25
Class with an Inner Class
26
Class with an Inner Class
27
Class with an Inner Class
28
Inner Class
Output
0
2
4
6
8
10
12
14
29
Static Inner Classes
• A normal inner class has a connection between its objects and
the outer class object that created the inner class object
– This allows an inner class definition to reference an instance variable, or
invoke a method of the outer class
• There are certain situations, however, when an inner class
must be static
– If an object of the inner class is created within a static method of the
outer class. {Builder design pattern}
– If the inner class must have static members
□ Instance variables of the outer class cannot be
referenced.
□ Non-static methods of the outer class cannot be
invoked.
30
Public Inner Classes
• If an inner class is marked public, then it can be used outside of
the outer class
– Create an object using an instance of the outer class {non-static}
– Use the Outer class’ name to access the inner class {static}
BankAccount account = new BankAccount();
BankAccount.Money amount = account.new Money("41.99");
OuterClass.InnerClass innerObject = new OuterClass.InnerClass();
31
Nested Inner Classes
• It is possible to nest an inner class within another inner class
• This however makes the notation for accessing the nested inner class
longer.
public class A{ A aObject = new A();
--- A.B bObject = aObject.new B();
public class B{ A.B.C cObject = bObject.new C();
---
public class C{
32
Inheriting Inner Classes
• It is possible to inherit an outer class that has an inner class
• If you derive (inherit) an outer class then the inner class is
automatically inherited.
– The inner class cannot be overridden.
33
Anonymous Classes
• If an object is to be created, but there is no need to name the
object's class, then an anonymous class definition can be used
– The class definition is embedded inside the expression with the new
operator
• Anonymous classes are sometimes used when they are to be
assigned to a variable of another type
34
Anonymous Classes
35
Anonymous Classes
36
Anonymous Classes
37
Threads & Multithreading
• A thread is a separate computation process.
– Threads can be thought of as computations that execute in parallel.
– A thread is a single sequential flow of control within a program.
– Thread does not have its own address space but uses the memory and other
resources of the process in which it executes.
– There may be several threads in one process
• Characteristics of threads
– Threads are lightweight processes as the overhead of switching between
threads is less
– The can be easily spawned
38
Threads & Multithreading
• We have experienced threads
• The Java Virtual Machine spawns a thread when your program is run called the Main Thread
39
Threads & Multithreading
• Multithreading is a programming concept where a program
(process) is divided into two or more subprograms (process),
which can be implemented at the same time in parallel
• Why do we need threads?
– To enhance parallel processing
– To increase response to the user
– To utilize the idle time of the CPU
– Prioritize your work depending on priority
• E.g.
– Video Games
– Web Server
• The web server listens for request and serves it
40
Threads & Multithreading
Single Thread MultiThread
41
Threads in Java
• Java contains a Thread class and a Runnable interface.
– There are 2 ways we can use threads
• extending the class Thread.
public class MyThreadClass extends Thread{.. }
• Implementing Runnable interface.
public class MyThreadClass implements Runnable{.. }
Note: It is usually more preferred to implement the Runnable Interface so that we can extend
properties from other classes
• The Thread class and Runnable interface contains the method
run().
– The public void run() method acts like the main method of a traditional
sequential program.
– We must override or implement the run() method so that our thread
can perform the actions we need.
42
Thread Lifecycle
When threads are created they may go The states of threads may be controlled
through the following states. by these methods.
New (Newborn) start()
Runnable yield()
Running suspend(), sleep(), wait()
Blocked resume(), notify()
Terminated (Dead) stop()
43
Thread Lifecycle
• Example
class mythread implements Runnable{
public void run(){
System.out.println(“Thread Started”);
}
}
class mainclass {
public static void main(String args[]){
Thread t = new Thread(new mythread()); // This is the way to instantiate a
thread implementing runnable interface
t.start(); // starts the thread by running the run method
}
}
• Calling t.run() does not start a thread, it is just a simple method call.
• Creating an object does not create a thread, calling start() method creates the
thread.
44
Producer Consumer
• Let us examine a simple producer consumer example
• In this example
– We have a producer thread that creates a random number.
– We also have a consumer thread that consumes the random number.
45
Producer Consumer
• The main method of the producer consumer creates two threads.
– One producer thread
– One consumer thread
Something’s fishy
with our results…
46
Synchronization
• Multithreading introduces an asynchronous behavior to your programs.
• We must force synchronicity if needed.
• This is done by using the keyword synchronized
• Synchronization in java is the capability of controlling the access of a shared
resource by multiple threads.
• Why do we use synchronization?
– To prevent thread interference
– To prevent consistency problems
– To prevent data corruption
47
Synchronization
• How it works.
• When a thread begins to execute a synchronized method it automatically acquires
a lock on that object.
• The lock is relinquished when the method ends.
• Only one thread can have the lock at a particular time
• Therefore only one thread can execute the synchronized instance method of the
same object at a particular time.
– Synchronization allows only one thread to perform an operation on a object at a time.
– If multiple threads require an access to an object, synchronization helps in maintaining
consistency.
48
Synchronized Producer Consumer
• This version of the producer consumer has a single stacked buffer
• The producer adds data to the buffer and waits if it is full
• The consumer takes data from the buffer and waits if empty
• To fully synchronize this multithreaded program we need
• Synchronized
– Makes a method synchronous
• Wait()
– Forces the thread to go into the blocked state
• Notify() / NotifyAll()
– Forces the thread back into the active state.
49
Synchronized Producer Consumer
• How the program works
Prod • I will produce a number
• Is the buffer full? Buffer
produce() • If yes then I must wait for the
consumer
• If not then Add() the number to Add()
the buffer and notify. Remove()
• I will consume a number
Con
• Is the buffer empty?
• If yes then I must wait for the
consume() producer
• If not then Remove() the
number from the buffer
and notify.
50
Synchronized Producer Consumer
51
Synchronized Producer Consumer
52
Synchronized Producer Consumer
53
Other Methods
Method Meaning
Thread currentThread() returns a reference to the current thread
Void sleep(long msec) causes the current thread to wait for msec milliseconds
String getName() returns the name of the thread.
Int getPriority() returns the priority of the thread
returns true if this thread has been started and has not Yet died.
Boolean isAlive()
Otherwise, returns false.
Void join() causes the caller to wait until this thread dies.
comprises the body of the thread. This method is overridden by
Void run()
subclasses.
Void setName(String s) sets the name of this thread to s.
Void setPriority(int p) sets the priority of this thread to p.
54
Thread Priorities
• In java, each thread is assigned a priority, which affects the order in which it
is scheduled for running.
• Java permits us to set the priority of a thread using the setPriority() method
as follows:
ThreadName.setPriority(intNumber);
• The intNumber may assume one of these constants or any value between 1
and 10.
• The intNumber is an integer value to which the thread’s priority is set. The
Thread class defines several priority constants:
– MIN_PRIORITY : 1
– NORM_PRIORITY : 5
– MAX_PRIORITY : 10
• The default setting is NORM_PRIORITY.
55
Self-Test (2)
• 프로젝트 명: Project11_2
– git commit –m “Project11_2”
– 당일 밤 12시까지 제출
• 이전 슬라이드의 Producer Consumer 예제를 Nested Class로 변환한다.
• Self-Test에서 비어 있는 ProdConSelfTest Class에서 수행해야하는 작업은 아래와 같다.
– 클래스에는 아래의 3개 인스턴스 변수가 있어야한다.
• Private Buffer buffer
• Private Producer producer
• Private Consumer consumer
– 아래와 같은 동작을 수행하는 인자가 없는 생성자를 생성한다.
• 크기가 15인 새로운 buffer.
• 새로운 producer.
• 새로운 consumer.
– Producer와 Consumer Class를 private inner class로 추가한다.
– Producer와 Consumer Inner class는 쓰레드를 사용한다.
– produc와 consume의 쓰레드를 시작하도록 하는 startThreads() 메소드를 작성한다.
56
Self-Test (2)
• 아래처럼 Console 창에 출력되는지 확인한다.
(출력되는 모양은 정확하게 일치하지 않을 수 있다.)
57