Compiled Module CPEPRO2
Compiled Module CPEPRO2
CPEPRO2 OBJECT-ORIENTED
PROGRAMMING
Course Description:
This course is a continuation of the subject Programming Logic and Design or CPEPRO1. It
introduces methods and later progresses to the discussion of the different concepts in Object-oriented
Programming using Java Language.
Single array
• Arrays are used to store multiple values called elements in a single variable, instead of
declaring separate variables for each value. The values must be of the same type.
Advantages:
• Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
• Random access: We can get any data located at an index position.
Disadvantage
• Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at
runtime. To solve this problem, collection framework is used in Java which grows
automatically.
Example:
Nature: Individual
General Code the following
Instruction:
Requirement: Submit a softcopy through Canvas labeled as Module 1 Assessment. This
should be an ATTACHMENT in MSWord format.
Duration: 4 hours
A program that lets the user enter a 4x4 matrix which accepts only 1 or 0.
Sample output:
Enter matrix:
1 1 0 1
1 0 1 0
1 1 0 1
0 0 0 1
[R]ow or [C]ol? R
Enter row/col: 2
Result:
1 1 0 1
0 1 0 1
1 1 0 1
0 0 0 1
The popular object-oriented languages are Java, C#, PHP, Python, C++,
etc.
OOP SYSTEM
Object means a real-world entity such as a pen, chair, table, computer, watch,
etc.
❖ Object
❖ Class
❖ Inheritance
❖ Polymorphism
❖ Abstraction
❖ Encapsulation
OBJECT
Objects can communicate without knowing the details brand: Samsung call
of each other's data or code. The only necessary thing color: BLACK turnOn
is the type of message accepted and the type of turnOff
RAM: 4 GB
response returned by the objects.
ROM: 64 GB sendMail
b.) behavior.
4. The object is an instance of a class.
CLASS
color: turnOn
RAM: turnOff
ROM: sendMail
CLASS contains:
1. Fields
2. Methods
3. Constructors
4. Blocks
5. Nested class and interface
CLASS vs OBJECT, a view from the top
DIFFERENTIATE A CLASS FROM AN OBJECT USING
THE FOLLOWING TABLE:
CLASS OBJECT
Memory
consumption
Number (how many)
Has a current state
Behavior
Existence (logical/real
or real-time)
CODING:
“MIRROR ME” activity
Creating a class:
data field – is part of the class’s state in this case, life. A “non-static”
variable in a class is called instance variable which means all instantiated
objects will have their own life variable.
private – access modifier which means it is only accessible to the class
Instance variables
constructor – a special method that has the same name as the class. Its function
is to initialize an instantiated object
If not explicitly defines, java creates one for you.
Numeric field are set to 0, character fields are set to Unicode ‘\u0000’, Boolean
fields to false and object fields such as String to null.
DIFFERENTIATE STATIC
FROM NON-STATIC
Static Non-static
static is a keyword No keyword used
class variables / static variables instance variable / non-static variable
instantiate 10 objects, only one copy of the Instantiate 10 objects, only one copy of the
method exist and method does not receive method exist but the method receives
a this reference a this reference that contains the address
of the object currently using it
every instance of a class shares separate memory location for
the same copy of any class variables each non-static field in each instance
Inheritance
Call via
Contacts
Call via
Browser
ENCAPSULATION
change
Version()
ABSTRACTION
For example, when you consider the case of e-mail, complex details such as
what happens as soon as you send an e-mail, the protocol your e-mail server
uses are hidden from the user. Therefore, to send an e-mail you just need to
type the content, mention the address of the receiver, and click send.
https://www.javatpoint.com/
https://www.tutorialspoint.com/
Farrell, Java Programming
METHOD
OVERLOADING
Prepared by: Meynard Soriano, CpE, MIT
Description
• This module will review you on static methods which you have
taken in your course Java 1. It progresses to method overloading
which is an important principle in OOP.
Objectives:
At the end of this module, the students must have:
1. defined what is method overloading, and
2. applied method overloading on static methods, mutators and
accessors.
•Let us review methods. We have
been using methods in the
previous modules. To strengthen
your knowledge in methods, the
succeeding slides will help you
recall what was discussed.
WHAT IS A METHOD?
• A method is a program module or block that
contains a series of statements that can be
carried out when called.
• Example:
➢main
➢constructors
➢mutators
➢accessors
WHO IS THE CALLER?
WHO WAS CALLED?
• To execute a method, you invoke or call it in
your program
• The act of calling a method makes a “method
call”.
• The method call invokes(to be executed by the
computer) the called method.
• The calling method is also known as a client
method. This is because a called method
provides a service for its client.
Illustration
Called
Client Method Method
Ex: Ex:
main(){ addAll(){
addAll(); …
} }
Guide questions in making a method:
}
Now, let us call the method inside
the main method.
public class ThisIsAClass{
public static void main(String [] args){
printAddress();
}
}
To print the address twice:
public class ThisIsAClass{
public static void main(String [] args){
printAddress();
printAddress();
}
}
Effect:
• The code is shorter because it promotes
software or code reuse. The code is also easier
to maintain. Editing the number of the house
will require you to edit one line of code only.
Parts of a method
Return type
Method header
Method name
Access specifier
Method Header
• A method header—A method’s header provides
information about how other methods can interact with
it. A method header is also called a declaration.
• It includes :
• The syntax (format = how to use)
• The parameter list
• The return type
• The method name
Method Body
• A method body between a pair of curly braces—The
method body contains the statements that carry out the
work of the method.
• A method’s body is called its implementation.
Technically, a method is not required to contain any
statements in its body, but you usually would have no
reason to create an empty method in a class.
• Sometimes, while developing a program, the
programmer creates an empty method as a placeholder
and fills in the implementation later. An empty method
is called a stub.
Access Specifier
• The access specifier for a Java method can be any of the
following modifiers: public, private, protected, or, if left
unspecified, package by default.
• public – if you want other methods and classes inside or
outside the package to use it
• private – if you want the method to be accessible inside
the class only
• package – if you want the method to be accessible
within the package( or the current project) only.
• protected – if you want the method or field to be
accessible not only to parent class but also child classes
static – a modifier keyword
• Aside from making the method in the example public, it
is also static.
• Making it static will not require you to instantiate an
object.
Parameters
(in the method header)
Example Method with one
parameter:
public class First
{
public static void main(String[] args)
{ argument
displayMessage(1);
System.out.println("First Java application");
parameter
}
public static void displayMessage(int x)
{
if(x==1) System.out.println(“You passed the value 1”);
else if(x==2) System.out.println(“You passed the value 2”);
}
}
Overloading a Method
write multiple methods in the same scope that have the same
name but different parameter lists
Example:
public static void overload(int a)
public static void overload(int a, double b)
public static void overload(String a)
Rules on Overloading Methods
AMBIGOUS:
public static void calculateInterest(int bal, double rate)
public static void calculateInterest(double rate, int bal)
***overloaded, different order but computer will be
confused what to use in case there is parameter type
casting.
Example: calculateInterest(5,6); What will the
computer use? Method 1 or 2?
this vs this()
“this” reference
NO PARAMETER:
public class Employee{
private int empNum; Employee partTimeWorker =
new Employee();
Employee(){
empNum = 999;}
}
WITH PARAMATER:
public class Employee{
private int empNum; Employee partTimeWorker =
new Employee(881);
Employee(int num){
empNum = num;}
}
OVERLOADING CONSTRUCTORS
public Employee(){
empNum = 999;}
}
“this()” constructor call
Constructor calls can be chained, meaning, you can
call another constructor from inside another
constructor.
Use the this() call for this type of chaining
There are a few things to remember when using the
this constructor call:
When using the this constructor call, IT MUST OCCUR AS THE
FIRST STATEMENT in a constructor
It can ONLY BE USED IN A CONSTRUCTOR DEFINITION. The
this call can then be followed by any other relevant
statements.
Challenge: Try this first (30 mins).
• the ability to create classes that share the attributes and methods of
existing classes but with more specific features
• enables one class to acquire all the behaviors and attributes of
another class
• Superclass/ base class/ parent
– Any class above a specific class in the class hierarchy.
– Common attributes
• Subclass/ derived class/ child
– Any class below a specific class in the class hierarchy.
– Class that inherits from a base class.
– Unique attributes
INHERITANCE DEMO:
• We are tasked to design 4 phones. The base phone or the phone that
will be the flagship will be called S22. S22FE is the cheapest. S22+ is
bigger in screen and has more colors to choose from. S22Ultra is as
big as S22+ but has more powerful camera, more Ram and more
colors to choose from.
• Program with the instructor and decide the features of the phone.
The instructor will point out the purpose of inheritance.
BENEFITS OF INHERITANCE
Output:
In superclass constructor
In subclass constructor
THE “SUPER” KEYWORD
▪ In this module, the student will learn how to handle common errors during
runtime. It will define exceptions and errors then give some tips to handle the
different types of exceptions.
▪ The Error class represents more serious errors from which your program
usually cannot recover.
▪ For example, there might be insufficient memory to execute a program.
▪ Usually, you do not use or implement Error objects in your programs.
▪ A program cannot recover from Error conditions on its own.
▪ The Exception class comprises less serious errors that represent unusual
conditions that arise while a program is running and from which the program
can recover.
▪ For example, one type of Exception class error occurs if a program uses an
invalid array subscript value, and the program could recover by assigning a
valid value to the subscript variable.
if(denominator == 0)
System.out.println("Cannot divide by 0");
else {
result = numerator / denominator;
System.out.println(numerator + " / " +
denominator + " = " + result);
}
▪ Programs that can handle exceptions appropriately are said to be more fault
tolerant and robust.
▪ Fault-tolerant applications are designed so that they continue to operate,
possibly at a reduced level, when some part of the system fails.
▪ Robustness represents the degree to which a system is resilient to stress and
able to continue functioning.
▪ Even if you choose never to use object-oriented exception-handling techniques
in your own programs, you must understand them because built-in Java
methods will throw exceptions.
catch(ArithmeticException mistake)
{
System.out.println(mistake.getMessage());
}
System.out.println("End of program");
▪ When you have actions you must perform at the end of a try…catch sequence,
you can use a finally block.
▪ The code within a finally block executes regardless of whether the preceding
try block identifies an exception.
▪ Usually, you use a finally block to perform cleanup tasks that must happen
regardless of whether any exceptions occurred and whether any exceptions
that occurred were caught.
▪ https://www.geeksforgeeks.org/types-of-exception-in-java-with-examples/
CPEPRO2 OBJECT-ORIENTED
PROGRAMMING
Computer programs usually are more user friendly and more fun to use when they contain
graphical user interface (GUI) components. GUI components are buttons, text fields, and other
components with which the user can interact. Java contains two sets of prewritten GUI components—
the Abstract Windows Toolkit (AWT) and Swing. AWT components are older, not as portable as
Swing components, and do not have a consistent appearance when used with different operating
systems.
Java Swing
• Java Swing is a part of Java Foundation Classes (JFC) that is used to create window-based
applications. It is built on the top of AWT (Abstract Windowing Toolkit) API and entirely written
in java.
• Unlike AWT, Java Swing provides platform-independent and lightweight components.
• The javax.swing package provides classes or java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc. (javatpoint.com, 2018).
AWT
• The Abstract Window Toolkit (AWT) is Java's original platform-dependent windowing, graphics,
and user-interface widget toolkit, preceding Swing. The AWT is part of the Java Foundation
Classes (JFC)
JFrame
JFrame class is a type of container which inherits the java.awt.Frame class. JFrame works like the
main window where components like labels, buttons, textfields are added to create a GUI.There are
two ways to create a frame:
1. by creating the object of Frame class (association)
2. by extending Frame class (inheritance)
We can write the code of swing inside the main(), constructor or any other method.
The JFrame is an object you instantiated inside your main method. The DisplayAllComponent is not
a JFrame subclass. Now try it in your IDE and describe the output. Screenshot the output and save it
in a Word document.
Now make a main method inside InheritedJFrame class. The main should look like this:
What you did is a class that inherited JFrame. You instantiated an object of type InheritedJFrame
inside your main method. This is the difference of association and inheritance. Now try it in your
IDE and describe the output. Screenshot the output and save it in a Word document.
Java JLabel
The object of JLabel class is a component for placing text in a container. It is used to display a
single line of read only text. The text can be changed by an application but a user cannot edit it
directly. It inherits JComponent class.
To try JLabel, encode the main method below inside your DisplayAllComponents class.
Now try it in your IDE and describe the output. Screenshot the output and save it in a Word
document.
JButton
The JButton class is used to create a labeled button that has platform independent
implementation. The application result in some action when the button is pushed. It inherits
AbstractButton class. To try JButton, edit the code above by including these lines of code after
f.add(l2).
FlowLayout
Rerun DisplayAllComponent’s main method. Now position the cursor to the rightmost edge of
the JFrame output and resize the frame going to the left. Describe what happened to the JButtons
and JLabels inside the JFrame. Screenshot the output and save it in a Word document. This layout is
called absolute and this is done by setting the layout to null.
Let us compare it with a layout controlled by the Layout Manager of Java. We will use the
layout FlowLayout. This is useful when placing components like JButtons and JLabels inside a
panel which is a container used to group components. To use the FlowLayout, change the line where
you set the layout to null (that is f.setLayout(null)) into f.setLayout(FlowLayout). The
practice is to group your components inside a JPanel (read on Jpanel vs JFrame) then use a
FlowLayout to out lay the components.
Now try it in your IDE and describe the output before and after resizing the JFrame. Screenshot the
output and save it in a Word document.
There must be a mechanism in your program to handle such events. They are called event handlers.
To handle an event:
1. Register the component with a listener.
Button
public void addActionListener(ActionListener a){}
MenuItem
public void addActionListener(ActionListener a){}
TextField
public void addActionListener(ActionListener a){}
public void addTextListener(TextListener a){}
2. Other class
3. Anonymous class
b1.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
l1.setText("Button Clicked!");
}
});
Now try it in your IDE and describe the output. Screenshot the output and save it in a Word
document.
ASSIGNMENT:
Read on 1 and 2 of putting the event handler (Within Class and Other Class) then demonstrate.
https://www.javatpoint.com/images/java-multithreading.png
▪ Process-based Multitasking (Multiprocessing)
1. Each process has an address in memory. In other words, each
process allocates a separate memory area.
2. A process is heavyweight.
3. Cost of communication between the process is high.
4. Switching from one process to another requires some time
for saving and loading registers, memory maps, updating
lists, etc.
▪ Thread-based Multitasking (Multithreading)
1. Threads share the same address space.
2. A thread is lightweight.
3. Cost of communication between the thread is low.
▪ A thread can be in one of the five states. According to sun, there
is only 4 states in thread life cycle in java new, runnable, non-
runnable and terminated. There is no running state.
▪ New
▪ Runnable
▪ Running
▪ Non-Runnable (Blocked)
▪ Terminated
A thread can be in one of the following states:
▪ NEW – a thread that has not yet started is in this state.
▪ RUNNABLE – a thread executing in the Java virtual
machine is in this state.
▪ BLOCKED – a thread that is blocked waiting for a
monitor lock is in this state.
▪ WAITING – a thread that is waiting indefinitely for
another thread to perform a particular action is in this
state.
▪ TIMED_WAITING – a thread that is waiting for another
thread to perform an action for up to a specified
waiting time is in this state.
▪ TERMINATED- a thread that has exited is in this state.
// interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void sleep(); // interface method (does not have a body)
}
▪ The Runnable interface should be implemented by any class
whose instances are intended to be executed by a thread.
Runnable interface have only one method named run().
myRunnable.doStop();
}
}
https://www.javatpoint.com/multithreading-in-java
https://www.tutorialspoint.com/java/java_multithreading.htm
https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.Stat
e.html
https://www.w3schools.com/java/ref_keyword_implements.asp
SCHOOL OF INFORMATION TECHNOLOGY
CPEPRO2 OBJECT-ORIENTED
PROGRAMMING
The java.io package contains nearly every class we might ever need to perform input and
output (I/O) in Java. All these streams represent an input source and an output destination. The
stream in the java.io package supports many data such as primitives, object, localized characters,
etc. (Java - Files and I/O - Tutorialspoint, n.d.).
Stream
A stream is a series of data. There are two types of stream – the InPutStream amd the
OutPutStream and they provide a good support such as methods, classes and pre-defined constants
which a programmer can readily use.
1. InPutStream – this is used to read data from a source
2. OutPutStream – this is used for writing data into a destination
Helper Methods:
FileOutputStream
Here are two constructors which can be used to create a FileOutputStream object.
Helper Methods:
Example:
import java.io.*;
Example
import java.io.File; // Import the File class
The File class has many useful methods for creating and getting information about files. For example: