Oops in Java
Oops in Java
Object-Oriented Programming
Java
Margit ANTAL
Sapientia Hungarian University of Transylvania
2023
Goals
1. Java Language
2. Objects and classes
3. Static Members
4. Relationships between classes
5. Inheritance and Polymorphism
6. Interfaces and Abstract Classes
7. Exceptions
8. Nested Classes
9. Threads
10. GUI Programming
11. Collections and Generics
12. Serialization
Module 1
Java language
Java language
● History
● Java technology: JDK, JRE, JVM
● Properties
● Hello world application
● Garbage Collection
Short History
https://en.wikipedia.org/wiki
● 2017 - Java SE 9 /Java_version_history
JVM
Properties
● Object-oriented
● Interpreted
● Portable
● Secure and robust
● Scalable
● Multi-threaded
● Dynamic capabilities (reflection)
● Distributed
Hello World Application
1. Write the source code: HelloWorld.java
HelloWorld.class
java HelloWorld
Runtime
JVM
Garbage Collection
● Class
● Attributes and methods
● Object (instance)
● Information hiding
● Encapsulation
● Constructors
● Packages
Class
● Is a user-defined type
− Describes the data (attributes)
− Defines the behavior (methods) } members
● Syntax
<modifier>* class <class_name>{
<attribute_declaration>*
<constructor_declaration>*
<method_declaration>*
}
● Example
public class Counter {
private int value;
public void inc(){
++value;
}
public int getValue(){
return value;
}
}
Declaring Attributes
● Syntax
<modifier>* <type> <attribute_name>[= <initial_value>];
● Examples
public class Foo {
private int x;
private float f = 0.0;
private String name =”Anonymous”;
}
Declaring Methods
● Syntax
<modifier>* <return_type> <method_name>( <argument>* ){
<statement>*
}
● Examples
public class Counter {
public static final int MAX = 100;
private int value;
/* C language */ /* C language */
struct Date { Date d;
int year, month, day; d.day = 32; //invalid day
};
d.month = 2; d.day = 30;
// invalid data
d.day = d.day + 1;
// no check
Information Hiding
● The solution:
Client code must use setters and getters to access internal data
// Java language
public class Date { Date d = new Date();
private int year, month, day; // no assignment
public void setDay(int d){..} d.setDay(32);
public void setMonth(int m){..} // month is set
public void setYear(int y){..} d.setMonth(2);
public int getDay(){...} // no assignment
public int getMonth(){...} d.day = 30;
public int getYear(){...}
}
“-” means
-firstName: String state
private access
String
Button
Thread
The package statement
● Syntax:
package <top_pkg_name>[.<sub_pkg_name>]*;
● Examples:
package java.lang;
- statement at the beginning of the
source file
public class String{ - only one package declaration per
//... source file
} - if no package name is declared →
the class is placed into the default
package
The import statement
● Syntax:
package <top_pkg_name>[.<sub_pkg_name>]*;
● Usage:
import <pkg_name>[.<sub_pkg_name>]*.*;
● Examples:
● Class, encapsulation
● Class members:
○ attributes
○ methods
● Object, instance
● Constructor
● Package
● Import statement
Object-oriented programming
Types
● Primitive types
● Reference Type
● Parameter Passing
● The this reference
● Variables and Scope
● Casting
Java Types
− Primitive (8)
● Logical: boolean
● Textual: char
● Integral: byte, short, int, long
● Floating: double, float
− Reference
● All others
Logical - boolean
− Characteristics:
● Literals:
− true
− false
● Examples:
− boolean cont = true;
− boolean exists = false;
Textual - char
− Characteristics:
● Represents a 16-bit Unicode character
● Literals are enclosed in single quotes (' ')
● Examples:
− 'a' - the letter a
− '\t' - the TAB character
− '\u0041' - a specific Unicode character ('A') represented by
4 hexadecimal digits
Integral – byte, short, int, and long
− Characteristics:
● Use three forms:
− Decimal: 67
− Octal: 0103 (1x8^2+0x8^1+3x8^0)
− Hexadecimal: 0x43
● Default type of literal is int.
● Literals with the L or l suffix are of type long.
Integral – byte, short, int, and long
− Ranges:
Type Length Range
byte 1 byte -27..27-1
short 2 byte -215..215-1
int 4 byte -231..231-1
long 8 byte -263..263-1
Floating Point – float and double
− Characteristics:
● Size:
− float – 4 byte
− double – 8 byte
● Decimal point
− 9.65 (double, default type)
− 9.65f or 9.65F (float)
− 9.65D or 9.65d (double)
● Exponential notation
− 3.41E20 (double)
Java Reference Types
object day 0
month 0
year 0
(2) Explicit Attribute Initialization
The address
of the object
reference date1 ???
object day 20
month 6 0x01a2345
year 2000
(5) The reference is assigned to a variable
0x01a2345
object day 20
month 6
year 2000
Assigning References
● Two variables refer to a single object
MyDate date1 = new MyDate(20, 6, 2000);
MyDate date2 = date1;
0x01a2345 day 20
object month 6
year 2000
Parameter Passing
Pass-by-Value
public class PassTest{
public void changePrimitive(int value){
++value;
}
pt.changeObjectDay( oneDate, 12 );
System.out.println( oneDate.getDay() );
Output:
100
2016
12
The this Reference
● Usage:
− To resolve ambiguity between instance variables and
parameters
− To pass the current object as a parameter to another
method
The this Reference
● Logical operators
● Bitwise operators ( ~, ^, &, |, >>, >>>, << )
● String concatenation ( + )
String Types
● String
− Immutable – once created can not be changed
− Objects are stored in the Constant String Pool
● StringBuffer
− Mutable – one can change the value of the object
− Thread-safe
● StringBuilder
− The same as StringBuffer
− Not thread-safe
Object-oriented programming
Arrays
● Declaring arrays
● Creating arrays
● Arrays of primitive and reference type
● Initialization of elements
● Multidimensional arrays
Declaring Arrays
● What is an array?
− Group of data objects of the same type
● Arrays of primitive types:
int t[];
int [] t;
● Arrays of reference types:
Point p[];
Point[] p;
Creating Arrays
Primitive Type
//array creation
t = new int[10];
//array creation
t = new int[10];
Creating Arrays
Reference Type
● Example:
//array declaration
Point [] t;
● Rectangular arrays:
int [][] array = new int[3][4];
● Non-rectangular arrays:
int [][] array;
array = new int[2][];
array[0] = new int[3];
array[1] = new int[5];
Remember
sNumber:1
Class Product
counter: 2
p2 :Product
sNumber:2
public Product() {
counter++;
sNumber = counter;
}
}
Better solution
public class Product{
private int sNumber;
public Product() {
counter++;
sNumber = counter; System.out.println( Product.getCounter());
} Product p = new Product();
} System.out.println( Product.getCounter());
Output?
Accessing static members
Recommended:
<class name>.<member_name>
Output?
Static Members
public InstanceCounter(){
++counter;
}
System.out.println( InstanceCounter.getCounter());
private Singleton(){
}
static {
// e.g. read counter from a file
}
}
The final Keyword
● Class
− You cannot subclass a final class.
● Method
− You cannot override a final method.
● Variable
− A final variable is a constant.
− You can set a final variable only once.
− Assignment can occur independently of the
declaration (blank final variable).
Blank Final Variables
public Employee(){
ID = createID();
}
--------------------------------------------------
OUTPUT:
UP
RIGHT
DOWN
LEFT
Enumerations
public enum GestureType {
UP (0, "fel"),
RIGHT (1, "jobb"),
DOWN (2, "le"),
LEFT (3, "bal");
Output
UP, fel, 0
RIGHT, jobb, 1
DOWN, le, 2
LEFT, bal, 3
REMEMBER
● Static data
− belongs to the class
● Association (containment)
− Strong – Composition
− Weak – Aggregation
Relationships between classes
Composition
Association
Aggregation
Composition
Relationships between classes
Implementing Associations (1)
− One-to-one
− One-to-many
Relationships between classes
Implementing one-to-many relationship (1)
public class Student{
private final long ID;
private String firstname;
private String lastname;
//...
}
//...
}
Relationships between classes
Implementing one-to-many relationship (2)
public class Course{
private final long ID;
private String name;
public static final int MAX_STUDENTS = 100;
private Student[] enrolledStudents;
private int numStudents;
//...
}
Module 5
Inheritance, Polymorphism
Outline
● Inheritance
− Parent class
− Subclass, Child class
● Polymorphism
− Overriding methods
− Overloading methods
− The instanceof operator
− Heterogeneous collections
Problem: repetition in implementations
public Manager( … ){
// …
}
public String toString(){
// …
}
}
Inheritance - syntax
}
The subclass
● Opportunities:
1) add new data → department
2) add new methods → e.g. getDepartment()
3) override inherited methods → toString()
Invoking Parent Class Constructors
public class Employee{
protected String name;
protected double salary;
protected Date birthDate;
public Employee( String name, double salary, Date birthDate){
this.name = name;
this.salary = salary;
this.birthDate = birthDate;
}
//...
}
private Yes
default Yes Yes
protected Yes Yes Yes
public Yes Yes Yes Yes
Polymorphism - Overriding Methods
//...
Employee e1 = new Employee(“Endre”,2000,new Date(20,8, 1986));
Manager m1 = new Manager(“Johann”,3000,
new Date(15, 9, 1990),”Sales”);
//...
System.out.println( createMessage( e1 ) );
System.out.println( createMessage( m1 ) );
Liskov Substitution!
Heterogeneous Arrays
// print employees
for( Employee e: emps ){
System.out.println( e.toString() );
}
// count managers
int counter = 0;
for( Employee e: emps ){
if( e instanceof Manager ){
++counter;
}
}
Static vs. Dynamic type of a reference
//Solution
System.out.println( ((Manager) e).getDepartment() );// CORRECT
//Better Solution
if( e instanceof Manager ){
System.out.println( ((Manager) e).getDepartment() );
}
The instanceof Operator
//expressions
a instanceof Animal → true
a instanceof Mammal → true
a instanceof Bear → true
a instanceof Date → false
Polymorphism
Overloading Methods
● Inheritance
− Subclass opportunities
● Polymorphism
− Overriding methods
− Overloading methods
− Polymorphic argument
− Heterogeneous collections
− Static vs. dynamic type
− The instanceof operator
Inheritance and Polymorphism
Methods Common to All Objects
Output?
An equals example
public class MyDate {
private int day;
private int month;
private int year;
}
The equals method
Output?
The equals method implements an
equivalence relation
● Reflexive
− x.equals(x):true
● Symmetric
− x.equals(y):true ↔ y.equals(x):true
● Transitive
− x.equals(y):true and y.equals(z):true →
x.equals(z):true
The toString method
● Characteristics:
− Converts an object to a String
− Override this method to provide information
about a user-defined object in readable
format
Wrapper Classes
int i = 420;
Too slow!!!
Module 6
Interfaces and Abstract Classes
Outline
● Interfaces
● Interfaces (since Java 8)
● Abstract classes
● Sorting
− Comparable interface
− Comparator interface
Interfaces
● Properties
− Define types
− Declare a set of methods (no implementation!) –
ADT – Abstract Data Type
− Will be implemented by classes
The Driveable Interface
@Override
public void forward() {
System.out.println("The bicycle moves forward");
}
@Override
public void turn( double angle) {
System.out.println("The bicycle turns "+angle+
" clockwise");
}
@Override
public void stop() {
System.out.println("The bicycle has been stopped");
}
}
Implementing the Driveable Interface
Interfaces
Iterator<String> it = l1.iterator();
while( it.hasNext() ){
System.out.print( it.next() + “ “);
}
-----------------------------------
a) Driveable a;
b) Driveable a = new Driveable();
c) Driveable t[] = new Driveable[ 3 ];
d) public void drive( Driveable d );
Interfaces vs. Classes
● Interface:
− User-defined type
− Set of methods
− No implementations provided
− Cannot be instantiated
● Class:
− User-defined type
− Set of data and methods
− All the methods are implemented
− Can be instantiated
Polymorphic Argument
public class Utils{
}
Java Interface Static Method
}
Java Interface Static Method
@Override
public void draw() {
System.out.println("I am a square");
}
}
Abstract Classes vs. Classes
● Abstract class:
− User-defined type
− Set of data and methods
− Abstract and implemented methods
− Cannot be instantiated
− Designed to be subclassed
● Class:
− User-defined type
− Set of data and methods
− All the methods are implemented
− Can be instantiated
Abstract Classes vs. Classes vs. Interfaces
interface Comparable {
int compareTo(Object o);
}
x.compareTo(y):
0: x equal to y
positive: x > y;
negative: x< y;
The Comparable<T> interface
interface Comparable<T> {
int compareTo(T o);
}
Attempts to use a
different type are caught
at compile time!!!
The Comparable<T> interface
}
The Comparable<T> interface
Consistency
− For each class we can define only one natural ordering through the
Comparable interface
− We can define an unlimited number of ordering using the
Comparator interface
The Comparator<T> interface
interface Comparator<T> {
int compare (T x, T y);
}
The Comparator<T> interface (1)
@Override
public int compare(Point p1, Point p2) {
return Double.compare(
p1.distanceTo(origo),
p2.distanceTo(origo));
}
}
ArrayList<Point> points = new ArrayList<Point>();
points.add( new Point(1,2));
points.add( new Point(2,2));
points.add( new Point(1,3));
});
for( Point point: points){
System.out.println( point );
}
The Comparator<T> interface (3)
Lambda
Collections. sort(points,
(Point p1, Point p2) ->
{
final Point origo = new Point(0,0);
return Double.compare(p1.distanceTo(origo),
p2.distanceTo(origo));
}
);
● Define exceptions
● Exception handling: try, catch, and
finally
● Throw exceptions: throw, throws
● Exception categories
● User-defined exceptions
Exception Example
java AddArguments 1 2 3
Sum: 6
try{
// critical code block
// code that might throw exceptions
} catch( MyException1 e1 ){
// code to execute if a MyException1 is thrown
} catch( MyException2 e2 ){
// code to execute if a MyException2 is thrown
} catch ( Exception e3 ){
// code to execute if any other exception is thrown
} finally{
// code always executed
}
Call Stack Mechanism
try{
connectDB();
doTheWork();
} catch( AnyException e ){
logProblem( e );
} finally {
disconnectDB();
}
The code in the finally block is always executed (even in case of return
statement)
Closing resources
The finally clause (2)
Usage:
System.out.println(ClassName.countLines(“input.txt”));
The Handle or Declare Rule
Usage:
try{
System.out.println(ClassName.countLines(“input.txt”));
} catch( FileNotFoundException e ){
e.printStackTrace();
}
The throws Clause
Principles:
}
User-Defined Exception
● When?
− If a class is used only inside of another class
(encapsulation)
− Helper classes
Nested Classes
Iterator it = list.createIterator();
while( it.hasNext() ){ Factory Method
System.out.println( it.next() ); Design Pattern
}
1. Solution – Non-static Nested Class
public class Slist{
private Element head;
//...
● Definition
● Creation: Thread and Runnable
● Synchronization
● Executors and thread pools
What are threads?
● Operating Systems
- lightweight process
- runs in the address space of a process
- has its own program counter (PC)+stack
- shares code and data with other threads
● Object-oriented Programming
- an object – an instance of the class Thread
What are threads?
Threads
java.lang.Thread = Infrastructure(PC+Stack)
java.lang.Runnable = Code
Thread's creation (1)
public class MyRunnable implements Runnable{
private int id;
public MyRunnable(int id ){
this.id = id;
}
…
MyRunnable r = new MyRunnable(1);
Thread t = new Thread( r );
Starting the thread
t.start();
Calls the thread object's run method
Thread's creation (1)
Output?
Thread's creation (2)
class MyThread extends Thread {
private int id;
…
Thread t = new MyThread(1);
t.start();
Thread's creation (2)
Usage:
Output?
Example (2)
public class MyFirstRunnable implements Runnable{
@Override
public void run() {
System.out.println("In a thread");
}
}
Usage:
Runnable runnable = new MyFirstRunnable();
for(int i = 0; i<25; i++){
new Thread(runnable).start();
}
Output?
Operations on threads
try {
Thread.sleep(1000);
} catch (InterruptedException e){
e.printStackTrace();
}
sleep()
try {
Thread.sleep(1000);
} catch (InterruptedException e){
e.printStackTrace();
}
Thread2
Need for synchronization
class Counter {
private int value;
import java.util.concurrent.atomic.AtomicInteger;
}
Synchronized Blocks
● Long
● Double
Executors and thread pools
CPU cores
Linux:
CPU info
$cat /proc/cpuinfo
− Eclipse
GUI Programming
Swing
Outline
JMenuItem
JButton
JLabel
Container
JPanel
JFrame
contains a picture
The first GUI program
JFrame
● FlowLayout
● BorderLayout
● GridLayout
● GridBagLayout
Layout Managers
GridLayout
public static JPanel createPanel( int n){
JPanel panel = new JPanel();
panel.setLayout(new GridLayout( n, n));
for( int i=0; i<n; ++i){
for( int j=0; j<n; ++j){
panel.add( new JButton
("("+i+","+j+")"));
}
}
return panel;
}
Creating UI
● Aggregation
− FrameAggregation
● Inheritance
− FrameInheritance
Creating UI
Aggregation
public class FrameAggregation {
frame.setJMenuBar(createMenu());
Dialogs
JOptionPane (1)
JOptionPane.showMessageDialog(
Component parent, String message);
Dialogs
JOptionPane (2)
int result =
JOptionPane.showConfirmDialog(
Component parent, String message);
Result:
YES_OPTION (0), NO_OPTION (1), CANCEL_OPTION (2)
Dialogs
JOptionPane (3)
String value=
JOptionPane.showInputDialog("Please input a value");
Dialogs
JOptionPane (4)
String options[]={"Apple", "Grape", "Strawberry"};
http://docs.oracle.com/javase/tutorial/uiswing/components/border.htm
l
Custom properties
Frame
describe what happened Panel
interaction
Event Types
● Low level
− Window
− Keyboard
− Mouse
● High level
− ActionEvent
− ItemEvent
●
`
Event Handling
Event Handler1
actionPerformed( ActionEvent e){
...
}
Event Handler2
actionPerformed( ActionEvent e){
...
}
Delegation Model
● GUI components trigger the handlers for the type of event that
has occurred
Event handler
public DrawComponent(){
this.addMouseListener(new MouseAdapter(){
@Override
public void mousePressed(MouseEvent e) {
points.clear();
points.add( new Point( e.getX(), e.getY()));
}
});
this.addMouseMotionListener(new MouseMotionAdapter(){
@Override
public void mouseDragged(MouseEvent e) {
points.add( new Point( e.getX(), e.getY()));
DrawComponent.this.repaint();
}
});
}
…
}
Example
Custom Component
public class DrawComponent extends JComponent{
//...
@Override
public void paint(Graphics g) {
g.setColor(color);
if( points != null && points.size()>0){
Point startPoint = points.get(0);
for( int i=1; i<points.size(); ++i ){
Point endPoint = points.get(i);
g.drawLine(startPoint.x, startPoint.y,
endPoint.x, endPoint.y);
startPoint = endPoint;
}
}
}
● General listeners
− ComponentListener
− FocusListener
− MouseListener
● Special listeners
− WindowListener
− ActionListener
− ItemListener
`
Event adapter classes
● Problem:
− Sometimes you need only one event handler method, but the
listener interface contains several ones
− You have to implement all methods, most of them with empty ones
● Solution:
− An Event Adapter is a convenience class
− Implements all methods of a listener interface with empty methods
− You extend the adapter class and override that specific method
Event Adapter Classes
Example
}
GUI Programming
JavaFX
Sources:
● https://docs.oracle.com/javafx/2/events/jfxpub-events.htm
● http://tutorials.jenkov.com/javafx
● https://www.tutorialspoint.com/javafx
Outline
● Creating UI
○ Declarative UI - FXML
○ Programmatic - Java
● Event Handling
Cross-platform
source
Stage
@Override
public void start(Stage primaryStage) throws Exception{
Parent root =
FXMLLoader.load(getClass().getResource("sample.fxml"));
primaryStage.setTitle("First App");
primaryStage.setScene(new Scene(root, 300, 275));
primaryStage.show();
}
1. Declarative UI - FXML
2. Programmatic UI - Java
1. Declarative UI
1.
3.
2.
FXML - Adding UI elements
@Override
public void start(Stage primaryStage) throws Exception{
Parent root =
FXMLLoader.load(getClass().getResource("sample.fxml"));
primaryStage.setTitle("Hello World");
primaryStage.setScene(new Scene(root, 300, 275));
primaryStage.show();
}
FXML - Control properties
<TextField
fx:id="inputText"
prefWidth="100.0" />
<Button
fx:id="okBtn"
alignment="CENTER_RIGHT"
onAction="#refresh"
text="OK"
textAlignment="CENTER" />
FXML - Event handling
<TextField
public class Controller {
fx:id="inputText" public void refresh(ActionEvent e){
prefWidth="100.0" /> Button button = (Button)e.getSource();
// ...
}
<Button }
fx:id="okBtn"
alignment="CENTER_RIGHT"
onAction="#refresh"
text="OK" ActionEvent
textAlignment="CENTER" />
MouseLogger application
<GridPane fx:controller="sample.Controller"
xmlns:fx="http://javafx.com/fxml"
alignment="center" hgap="10" vgap="10"
onMouseMoved = "#handleMouseMoved"
onMousePressed = "#handleMousePressed"
onMouseReleased = "#handleMouseReleased"
onMouseDragged = "#handleMouseDragged">
Event handling - Mouse Events (2)
submitButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent actionEvent) {
// handle the event
}
});
}
JavaFX - Event handling
● Foreground events
○ require direct interaction of a user
○ interactions with the UI
● Background events
○ Operating system interruptions
○ Timer expiry
Event Driven Programming
EventDispatcher:
○ receives events
○ notifies interested objects
EventQueue EventHandler
1. ActionEvent notify
Event 2. MouseEvent void handle(Event event){
3. KeyEvent //…
4. ….. }