OOP JAVA Master
OOP JAVA Master
Programming (OOP)
Teaching Assistant: Nourchene OUERHANI
([email protected])
Objectives
1. Understand the fundamental concepts of object oriented
programming
2. Illustrate and understand inheritance concepts.
3. Understand the impact of exception handling to prevent abnormal
termination of program.
4. Understand the Java principles, as well as the syntax that will be
needed for the rest of the program.
5. Have a fairly complete idea of the notions you need to know in
order to be able to program in Java.
Nourchene OUERHANI 2
Object Oriented Programming (OOP) Plan
PLAN
1. OOP Introduction
2. JAVA language syntax
3. OOP Fundamentals: JAVA OOPL
4. Exception Handling
Nourchene OUERHANI
Object Oriented Programming (OOP) Plan
Object-oriented programming
Introduction
1. What is OOP?
2. What is JAVA?
3. JAVA uses
4. JAVA Environment
Nourchene OUERHANI 4
Object Oriented Programming (OOP) Object-oriented programming Introduction
Brainstorming TIME !
Website: https://app.wooclap.com
OOP?
Code: OOPJAVA
Nourchene OUERHANI 5
Object Oriented Programming (OOP) Object-oriented programming Introduction
What is OOP?
● Programming paradigm.
● The program is written as a set of interactive classes and
objects.
● Object is the basic and most fundamental entity.
● Only objects are used for all computations.
● Data is prioritized over function.
Nourchene OUERHANI 6
Object Oriented Programming (OOP) Object-oriented programming Introduction
Pair work
Programming Paradigms?
Nourchene OUERHANI 7
Object Oriented Programming (OOP) Object-oriented programming Introduction
Pair work
OOP VS POP
Nourchene OUERHANI 8
Object Oriented Programming (OOP) Object-oriented programming Introduction
OOP vs POP
● It prioritizes data over function. ● It prioritizes function over data.
● Code easy to modify and maintain ● "Spaghetti" code → Difficulty of
● Offers the feature to reuse any Maintaining and adding new
existing codes in it by utilizing a features
feature known as inheritance. ● No feature of reusing codes
● It achieves inheritance in three ● It does not provide any
modes- protected, private, and inheritance.
public. ● Does not offer any method of
● Hiding data is possible due to the hiding data.
abstraction. ● It is not very suitable for solving
● It is suitable for solving any big or any big or complex problems.
complex problems.
Nourchene OUERHANI 9
Object Oriented Programming (OOP) Object-oriented programming Introduction
OOP vs POP
Example:
We want to make a personnel management program for an IT
company.
In this company we can find:
● Engineers: F.Name , L.Name, Phone number, Specialty, list of
diplomas, Hire date, Salary
● Technicians: F.Name , L.Name, Phone number, Specialty, Hire date,
Salary
● Directors: F.Name , L.Name, Phone number, fax number, office
number, service, Salary
Nourchene OUERHANI 10
Object Oriented Programming (OOP) Object-oriented programming Introduction
OOP vs POP
Example:
1st solution: Procedural Oriented Programming
→ What do we want to do?
Struct firstName readEngineer() Struct firstName readTechnician()
Engineer lastName displayEngineer() Technician lastName displayTechnician()
phonenNumber calcSalary() phonenNumber calcSalary()
salary salary
hireDate hireDate
diplomaList speciality
speciality
Nourchene OUERHANI 11
Object Oriented Programming (OOP) Object-oriented programming Introduction
OOP vs POP
Example:
2nd solution: Object-oriented programming class Staff Class name
firstName
→ What are we talking about? lastName Class attributes
salary
phoneNumber
readStaff()
displayStaff()
Class methods
hireDate faxNumber
hireDate
specialty officeNumber
specialty
diplomaList service
Nourchene OUERHANI 12
Object Oriented Programming (OOP) Object-oriented programming Introduction
JAVA History
1 2
+ 9 0
James Sun
9 0
Gosling Microsystems
5 9
What is JAVA?
● Class based, object oriented programming language.
● High level language.
● Can be considered both a compiled and an interpreted
language.
● Uses syntax that is extremely similar to the C language.
● Platform-independent: write once, run anywhere
→ run on any device that has a Java Virtual Machine (JVM)
installed.
● Portable: it is easy to migrate Java bytecode between
different platforms.
Nourchene OUERHANI 14
Object Oriented Programming (OOP) Object-oriented programming Introduction
What is JAVA?
● A Java programmer writes his source code, in
the form of classes, in files whose extension is Example
“.java” Source Code test.java
● The Javac compiler then converts this source
code into bytecode and saves the outcome in a Compiler javac test.java
file with the extension ".class"
● The bytecode must be interpreted by the Java Bytecode test.class
virtual machine (JVM) which then transforms
the compiled code into machine code
Interpreter Java test
understandable by the operating system.
→ This is the reason why Java is a portable Machine Code Virtualisation
language.
NB: The bytecode remains the same regardless Operating Operating
System System
of the execution environment.
Nourchene OUERHANI 15
Object Oriented Programming (OOP) Object-oriented programming Introduction
Why Java?
TIOBE Index April 2023 (www.tiobe.com/tiobe-index/)
Nourchene OUERHANI 16
Object Oriented Programming (OOP) Object-oriented programming Introduction
Why Java?
Stack Overflow Developer Survey 2022
Nourchene OUERHANI 17
Object Oriented Programming (OOP) Object-oriented programming Introduction
Why Java?
GitHub Octoverse Report 2022
Nourchene OUERHANI 18
Object Oriented Programming (OOP) Object-oriented programming Introduction
Why Java?
IEEE Spectrum Ranking 2022
Nourchene OUERHANI 19
Object Oriented Programming (OOP) Object-oriented programming Introduction
Why Java?
PYPL PopularitY of Programming Language Index 2023
Nourchene OUERHANI 20
Object Oriented Programming (OOP) Object-oriented programming Introduction
Why Java?
Nourchene OUERHANI 21
Object Oriented Programming (OOP) Object-oriented programming Introduction
JAVA Uses
● Desktop GUI applications
● Web applications
● Mobile applications
● Enterprise applications like ERP
● Banking, Insurance, Ecommerce, etc.
● Scientific applications
● Embedded Systems, Big Data Technologies, Distributed
Applications, Cloud-based Applications
● Web servers and Application servers, Software Tools, and Gaming
Applications etc.
Nourchene OUERHANI 22
Object Oriented Programming (OOP) Object-oriented programming Introduction
Nourchene OUERHANI 23
Object Oriented Programming (OOP) Object-oriented programming Introduction
Advantages
1. Platform Independence: One of the biggest advantages of Java is its ability to
run on any device that has a JVM installed.
Nourchene OUERHANI 24
Object Oriented Programming (OOP) Object-oriented programming Introduction
Advantages
1. Large Standard Library: Java provides a large standard library that includes a
wide range of tools and utilities for developing applications. This can help to
streamline development and reduce the amount of time and effort required
to build a complex application.
Nourchene OUERHANI 25
Object Oriented Programming (OOP) Object-oriented programming Introduction
Disadvantages
1. Performance: Java can be slower than other programming languages like C
or C++. This is because Java code is first compiled to bytecode and then
interpreted by the JVM at runtime.
4. Security: Java's popularity also makes it a popular target for hackers and
malware developers. While Java has many built-in security features, it is still
vulnerable to certain types of attacks.
Nourchene OUERHANI 26
Object Oriented Programming (OOP) Object-oriented programming Introduction
Java Environment
To be able to program in Java, JDK is needed, which represents the
environment in which the Java code is compiled so that the virtual
machine (JVM for Java Virtual Machine) can interpret it.
JDK contains:
● The Java compiler (javac)
● The archiver (jar)
● The documentation generator (javadoc)
● The debugger (jdb)
● The Java Runtime Environment (JRE).
Nourchene OUERHANI 27
Object Oriented Programming (OOP) Object-oriented programming Introduction
Java Environment
To compile and run a program in Java, there are two methods:
1. Call the commands directly on a console:
a. javac for compilation
b. java for execution
2. Use an Integrated Development Environment (IDE): This IDE, in
collaboration with the JDK, facilitates the realization of all the steps of
compilation and execution, thanks to a dedicated graphical interface.
There are several IDEs that can be used (Netbeans, Eclipse, Intellij,
JDeveloper, JBuilder...).
Nourchene OUERHANI 28
Object Oriented Programming (OOP) Object-oriented programming Introduction
Nourchene OUERHANI 29
Object Oriented Programming (OOP) Object-oriented programming Introduction
Other Views
Console
Nourchene OUERHANI 30
Object Oriented Programming (OOP) Object-oriented programming Introduction
Nourchene OUERHANI 33
Object Oriented Programming (OOP) Object-oriented programming Introduction
1. javac Hello.java
2. java Hello.java
3. javac Hello.class
4. java Hello.class
5. java Hello
Nourchene OUERHANI 34
Object Oriented Programming (OOP) Object-oriented programming Introduction
Activity 2:
Nourchene OUERHANI 36
Object Oriented Programming (OOP) Object-oriented programming Introduction
Activity 3:
In this activity, you will add arguments to the class.
1. Create in the same Helloworld project, a new package named
helloArgsPack, containing a Helloworld class which contains a
main method.
2. In the main method code, write:
System.out.println("Hello "+args[0]+"!");
3. To set arguments to the class, click the arrow next to the run icon
and select Run Configurations, or click the class you want to run,
and go to Run as -> Run Configurations
Nourchene OUERHANI 37
Object Oriented Programming (OOP) Object-oriented programming Introduction
Activity 3:
Nourchene OUERHANI 38
Object Oriented Programming (OOP) Plan
PLAN
1. OOP Introduction
2. JAVA language syntax
3. OOP Fundamentals: JAVA OOPL
4. Exception Handling
Nourchene OUERHANI
Object Oriented Programming (OOP) Plan
Code Example
public class Hello
{
static public void main(String[] args)
{
System.out.println("Hello");
}
}
Nourchene OUERHANI 41
Object Oriented Programming (OOP) JAVA language syntax
Code Example
public class Hello
{
static public void main(String[] args)
{
System.out.println("Hello");
}
}
A class should always start with an
uppercase first letter.
Java is case-sensitive: The terms
"Hello" and "hello" are different.
Nourchene OUERHANI 42
Object Oriented Programming (OOP) JAVA language syntax
Code Example
public class Hello
{
static public void main(String[] args)
{
System.out.println("Hello");
}
The }main() method is required in every Java program.
The method main() is the main entry point into a Java program; this is
where the processing starts. Also allowed is the signature public static
void main(String… args).
Each Java program has a class name that must correlate to the
filename, and each program must have the main() method.
Nourchene OUERHANI 43
Object Oriented Programming (OOP) JAVA language syntax
Example
public class Hello
{
static public void main(String[] args)
{
System.out.println("Hello");
}
}
Each code statement must end with a
semicolon ;
The curly braces { } marks the beginning and the end of a block of
code.
Nourchene OUERHANI 44
Object Oriented Programming (OOP) JAVA language syntax
Print Method
System.out.println("Hello");
● The println() method is used to output values or print text to the
screen.
Java Comments
● Java supports single-line and multi-line comments very similar to C
and C++.
● All characters inside any comment are ignored by Java compiler.
int number;
number= 15;
System.out.println(number);
Nourchene OUERHANI 47
Object Oriented Programming (OOP) JAVA language syntax
int x = 5;
int y = 6;
int z = 50;
System.out.println(x + y + z);
int x = 5, y = 6, z = 50;
System.out.println(x + y + z);
Nourchene OUERHANI 48
Object Oriented Programming (OOP) JAVA language syntax
int x, y, z;
x = y = z = 50;
System.out.println(x + y + z);
Nourchene OUERHANI 49
Object Oriented Programming (OOP) JAVA language syntax
Nourchene OUERHANI 50
Object Oriented Programming (OOP) JAVA language syntax
Nourchene OUERHANI 51
Object Oriented Programming (OOP) JAVA language syntax
Nourchene OUERHANI 52
Object Oriented Programming (OOP) JAVA language syntax
Nourchene OUERHANI 53
Object Oriented Programming (OOP) JAVA language syntax
short
● Size = 2 byte = 16 bits
● Stores whole numbers from -32,768 (-2^15) to 32,767 (2^15 - 1)
● Example: short s = 10000, short r = -20000
Nourchene OUERHANI 54
Object Oriented Programming (OOP) JAVA language syntax
long
● Size = 8 byte = 64 bits
● Stores whole numbers from -9,223,372,036,854,775,808 (-2^63) to
9,223,372,036,854,775,807 (2^63 - 1)
● Default value is 0L
● Example: long a = 100000L, long b = -200000L
Nourchene OUERHANI 55
Object Oriented Programming (OOP) JAVA language syntax
Nourchene OUERHANI 56
Object Oriented Programming (OOP) JAVA language syntax
Char
● Size = 2 bytes = 16 bits
● Stores single characters, such as 'a' or 'B'.
● Char values are surrounded by single quotes
Nourchene OUERHANI 57
Object Oriented Programming (OOP) JAVA language syntax
Nourchene OUERHANI 59
Object Oriented Programming (OOP) JAVA language syntax
Nourchene OUERHANI 60
Object Oriented Programming (OOP) JAVA language syntax
Nourchene OUERHANI 61
Object Oriented Programming (OOP) JAVA language syntax
Nourchene OUERHANI 62
Object Oriented Programming (OOP) JAVA language syntax
Nourchene OUERHANI 63
Object Oriented Programming (OOP) JAVA language syntax
Nourchene OUERHANI 64
Object Oriented Programming (OOP) JAVA language syntax
Nourchene OUERHANI 65
Object Oriented Programming (OOP) JAVA language syntax
Java Variables
1. Local Variable
● A variable declared inside the body of the method
● Used only within that method and the other methods in the class
aren't aware that the variable exists.
● A local variable cannot be defined with "static" keyword.
2. Instance Variable
● A variable declared inside the class but outside the body of the
method.
● It is not declared as static.
Nourchene OUERHANI 66
Object Oriented Programming (OOP) JAVA language syntax
Java Variables
4. Final variable
● Used to prevent overwriting existing values.
● Unchangeable and read-only
● To declare the variable as "final" or "constant", use the final keyword.
Nourchene OUERHANI 67
Object Oriented Programming (OOP) JAVA language syntax
Java Variables
public class Hello
{ static int staticVar=18;//static variable
final int constantVar= 26;
constantVar= 30; // will generate an error: cannot assign a value to a final
variable
public void methodLocalVar()
{ int localVar=10;//local variable
}
public static void main(String args[])
{ int instanceVar=125;//instance variable
} }
Nourchene OUERHANI 68
Object Oriented Programming (OOP) JAVA language syntax
To use the Scanner class, create an object of the class and use any of the
available methods found in the Scanner class documentation.
import java.util.Scanner; // Import the Scanner class form java.util package
public class Hello{
public static void main(String[] args) {
Scanner objectScanner= new Scanner(System.in); // Create a Scanner object
System.out.println("Enter first name");
String userName = objectScanner.nextLine(); // Read user input (String)
System.out.println("Username is: " + userName); // Output user input
}}
Nourchene OUERHANI 69
Object Oriented Programming (OOP) JAVA language syntax
Nourchene OUERHANI 70
Object Oriented Programming (OOP) JAVA language syntax
Nourchene OUERHANI 71
Object Oriented Programming (OOP) JAVA language syntax
= x = 5 x = 5
+= x += 3 x = x + 3
-= x -= 3 x = x - 3
*= x *= 3 x = x * 3
/= x /= 3 x = x / 3
%= x %= 3 x = x % 3
|= x |= 3 x = x | 3
^= x ^= 3 x = x ^ 3
Nourchene OUERHANI 73
Object Oriented Programming (OOP) JAVA language syntax
Nourchene OUERHANI 74
Object Oriented Programming (OOP) JAVA language syntax
Nourchene OUERHANI 75
Object Oriented Programming (OOP) JAVA language syntax
Nourchene OUERHANI 76
Object Oriented Programming (OOP) JAVA language syntax
if (condition) {
// block of code to be executed if the condition is true
}
Nourchene OUERHANI 77
Object Oriented Programming (OOP) JAVA language syntax
Nourchene OUERHANI 78
Object Oriented Programming (OOP) JAVA language syntax
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is
true
} else {
// block of code to be executed if the condition1 is false and condition2 is
false
}
Nourchene OUERHANI 79
Object Oriented Programming (OOP) JAVA language syntax
Nourchene OUERHANI 80
Object Oriented Programming (OOP) JAVA language syntax
It can be used to replace multiple lines of code with a single line, and is
most often used to replace simple if-else statements:
Nourchene OUERHANI 81
Object Oriented Programming (OOP) JAVA language syntax
Nourchene OUERHANI 82
Object Oriented Programming (OOP) JAVA language syntax
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
Nourchene OUERHANI 83
Object Oriented Programming (OOP) JAVA language syntax
Nourchene OUERHANI 84
Object Oriented Programming (OOP) JAVA language syntax
Nourchene OUERHANI 85
Object Oriented Programming (OOP) JAVA language syntax
while (condition) {
// code block to be executed
}
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
Nourchene OUERHANI 86
Object Oriented Programming (OOP) JAVA language syntax
do {
// code block to be executed
}
while (condition);
Nourchene OUERHANI 87
Object Oriented Programming (OOP) JAVA language syntax
do {
System.out.println(i);
i++;
}
Nourchene OUERHANI 88
Object Oriented Programming (OOP) JAVA language syntax
Initialization Expression: Initialize the loop counter to some value: int i=1;
Test Expression: In this expression, we have to test the condition. If the condition
evaluates to true then, we will execute the body of the loop and go to update
expression. Otherwise, we will exit from the for loop: i <= 10;
Update Expression: After executing the loop body, this expression
increments/decrements the loop variable by some value: i++; / i—- / i+2
Nourchene OUERHANI 89
Object Oriented Programming (OOP) JAVA language syntax
Nourchene OUERHANI 90
Object Oriented Programming (OOP) JAVA language syntax
The "inner loop" will be executed one time for each iteration of the "outer
loop":
// Outer loop
for (int i = 1; i <= 2; i++) {
System.out.println("Outer: " + i); // Executes 2 times
// Inner loop
for (int j = 1; j <= 3; j++) {
System.out.println(" Inner: " + j); // Executes 6 times (2 * 3)
}}
Nourchene OUERHANI 91
Object Oriented Programming (OOP) JAVA language syntax
The following example outputs all elements in the cars array, using a
"for-each" loop.
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String i : cars) {
System.out.println(i);
}
Nourchene OUERHANI 92
Object Oriented Programming (OOP) JAVA language syntax
Break
VS
Continue
Nourchene OUERHANI 97
Object Oriented Programming (OOP) JAVA language syntax
Java Arrays
Arrays are used to store multiple values in a single variable, instead of
declaring separate variables for each value.
To declare an array, define the variable type with square brackets:
String[] cars;
Nourchene OUERHANI 98
Object Oriented Programming (OOP) JAVA language syntax
Java Arrays
An array element is accessed by referring to the index number.
Array indexes start with 0:
● [0] is the first element.
● [1] is the second element, etc.
Nourchene OUERHANI 99
Object Oriented Programming (OOP) JAVA language syntax
Java Arrays
Use the index number to modify the value of a particular element.
Java Arrays
Loop through the array elements with the for loop, and use the
length property to specify how many times the loop should run.
Java Arrays
There is also a "for-each" loop, which is used exclusively to iterate
through elements in arrays.
String[] cars = {"Renault", "BMW", "Ford", "Mazda"};
for (String i : cars) {
System.out.println(i); for each String element (called i) in cars,
} print out the value of i.
PLAN
1. OOP Introduction
2. JAVA language syntax
3. OOP Fundamentals: JAVA OOPL
4. Exception Handling
Nourchene OUERHANI
Object Oriented Programming (OOP) Plan
1. Class
2. Object
3. Inheritance and composition
4. Abstraction
5. Interface
Class
● The mold, the plan, the recipe for any object.
● A template for several similar objects, sharing common
characteristics.
● A logical entity. It can't be physical.
● A class in Java can contain:
★ Fields
★ Methods
★ Constructors
★ Blocks
★ Nested class and interface
Object: Definitions
● An object is a real-world entity.
● An object is a runtime entity.
● An object is an entity that has state and behavior.
● An object is an instance of a class.
● We can create any number of objects of a class.
● It can be physical or logical (tangible and intangible).
Object: Definitions
● A physical object is tangible and has a physical presence in the world. It can be
seen, touched, and interacted with in a physical way.
○ Examples of physical objects include rocks, tables, chairs, and people.
● A logical object is intangible and does not have a physical presence in the
world. It exists only in the mind and is created through abstract thinking and
reasoning.
○ Examples of logical objects include concepts such as love, justice, and
democracy, as well as mathematical constructs like numbers and equations.
Object
In OOP, an object has three fundamental characteristics: state, behavior, and
identity.
● State: refers to the data or values that an object holds at a particular point in
time. This data can be stored in instance variables, which are defined within the
class and hold specific values for each object.
○ For example, if we have a class representing a person, the state of an object
of that class might include attributes such as the person's name, age, and
address.
● Behavior : refers to the actions or methods that an object can perform. These
methods can manipulate the object's state, interact with other objects, and
produce some kind of response.
○ For example, if we have an object representing a person, the behavior of
that object might include methods for walking, talking, eating, and
sleeping.
Nourchene OUERHANI 113
Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL
Object
● Identity: In most OOP languages, the responsibility of giving a
unique identifier or identity to an object is handled by the
language's runtime environment or the underlying virtual machine,
such as the Java Virtual Machine (JVM) or .NET Common Language
Runtime (CLR). This ID is used internally by the runtime
environment to manage the object's memory and state.
→ The developer does not need to worry about generating or
managing these identifiers themselves.
→ The developer is responsible for defining the object's behavior and
state, including any methods or instance variables that the object
will have.
Nourchene OUERHANI 114
Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL
Class VS Object
Class
Object
Class VS Object
Class
Object
Object
Syntax
This statement has three parts:
ClassName objectName = new ClassName();
1. Declaration
2. Instantiation
OR 3. Initialization
ClassName objectName;
Object: Example
Object: Instantiation
Creating an object of the class is called instantiation.
→ That means to specify the class name, followed by the object name, and use
the keyword new.
The new operator requires a single, postfix argument: a call to the constructor
of a class .
The new operator returns a reference to the object it created. This reference is
usually assigned to a variable of the appropriate type, like:
Object: Initialization
Here's the code for the Person This class contains a single constructor.
class:
The constructor in the Person class takes
public class Person { one integer arguments, as declared by
public int a = 0; the code (int a).
//constructor
The following statement provides 50 as
public Person(int x)
{ a = x; value for this argument:
} Person manObject=new Person (50);
}
Object
A Person object
personObject a 50
Object
public class Person{
int a = 50;
System.out.println(myObj2.a);
The name of the java file should match the class name.
● Main.java
● Person.java
Person.java Main.java
System.out.println(myObj1.a);
System.out.println(myObj2.a);
}}
Attributes
We used the term "variable" for x in the Person class.
Let’s create a class called "Person" with two attributes: age and height:
public class Person {
int age = 50;
float height = 180;
}
Attributes: Access
To access attributes:
● Create an object of the class
● Use the dot syntax (.)
The following example will create an object of the Person class, with the
name myObj. We use the age attribute on the object to print its value:
Attributes: Modification
Let’s set the value of age to 32: Let’s override the value of age:
public static void main(String[] args) public static void main(String[] args)
{ Person myObj = new Person(); { Person myObj = new Person();
myObj.age=32; myObj.age=14;
System.out.println(myObj.age);}} System.out.println(myObj.age);}}
Attributes: Modification
Let’s set the value of age to 32: Let’s override the value of age:
public static void main(String[] args) public static void main(String[] args)
{ Person myObj = new Person(); { Person myObj = new Person();
myObj.age=32; myObj.age=14;
System.out.println(myObj.age);}} System.out.println(myObj.age);}}
Attributes: Modification
Let’s set the value of age to 32: Let’s override the value of age:
public static void main(String[] args) public static void main(String[] args)
{ Person myObj = new Person(); { Person myObj = new Person();
myObj.age=32; myObj.age=14;
System.out.println(myObj.age);}} System.out.println(myObj.age);}}
Methods
● Block of code or collection of statements or a set of code grouped
together to perform a specific task or operation.
● Used to achieve the reusability of code.
● Written once and used many times.
● Provides the easy modification and readability of code.
● Executed only when it is called or invoked.
Methods Method
Signature
Methods
Method Signature: Every method has a method signature. It is a part of the
method declaration. It includes the method name and parameter list.
Access Modifier: Access specifier or modifier is the access type of the method. It
specifies the visibility of the method. Java provides four types of access modifiers:
● default: Java uses default access specifier, when we do not use any access
modifier in the method declaration. It is visible only from the same
package.
Methods
Return Type: Return type is a data type that the method returns. It may have a
primitive data type, object, collection, void, etc. If the method does not return
anything, we use void keyword.
Method Name: It is a unique name that is used to define the name of a method. It
must be corresponding to the functionality of the method. Suppose, if we are
creating a method for subtraction of two numbers, the method name must be
subtract(). A method is invoked by its name.
Method Body: It is a part of the method declaration. It contains all the actions to
be performed. It is enclosed within the pair of curly braces.
Nourchene OUERHANI 135
Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL
int myMethod(int x)
float myMethod(float x)
double myMethod(double x, double y)
Methods: Main
The main() is the starting point for JVM to start the execution of a Java program.
JVM will not execute the program without the main() method.
The syntax of the main() method is: public static void main(String[]args)
● public: public keyword must be used before the main() method so that JVM
can identify the execution point of the program. If private, protected, and
default are used before the main() method, it will not be visible to JVM.
● static: the main() method must be called without creating an object. Static
methods are the method which invokes without creating the objects, so no
need to create an object to call the main() method.
● void: In Java, every method has the return type. Void keyword acknowledges
the compiler that main() method does not return any value.
Methods: Main
main(): It is a default which is predefined in the JVM. It is called by JVM to
execute a program line by line and end the execution after completion of
this method.
String[] args: The main() method also accepts some data from the user.
It accepts a group of strings, which is called a string array.
Constructor
● A special method that is used to initialize objects.
● Called when an object of a class is created.
● Used to set initial values for object attributes.
Constructor: Types
Default constructor (no-arg constructor)
● A default constructor is called if there is no constructor available in
the class. In such case, Java compiler provides a default constructor.
● Default constructor provides the default values to the object like 0,
null, etc. depending on the type.
Syntax:
ClassName(){}
Constructor: Types
Default constructor (no-arg constructor)
Constructor: Types
Parameterized Constructors
Syntax:
ClassName(){
//block code
}
Nourchene OUERHANI 143
Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL
Constructor: Types
Parameterized Constructors
public class Person {
int personAge;
String personName;
public Person(String name, int age) {
personAge = age;
personName= name;
}
public static void main(String[] args) {
Person myObj = new Person("Ahmed", 23);
System.out.println(myObj.age);
System.out.println(myObj.name);}}
Constructor: Types
Difference between constructor and method in Java
Constructor Method
The constructor name must be same as the The method name may or may
A constructor must not have a return type. A method must have a return type
Modifiers
Encapsulation
To make sure that sensitive data is hidden from users.
● Declare class variables/attributes as private
● Provide public get and set methods to access and update the value of a
private variable
Getters and Setters
● private variables can only be accessed within the same class.
→ Access them by providing public get and set methods:
○ The get method returns the variable value
○ The set method sets the value.
● Syntax: Method starts with get or set, followed by the name of the variable,
with the first letter in upper case.
Nourchene OUERHANI 152
Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL
Encapsulation
public class Person{
class Main{
private String name;
public static void main(String[] args){
//getter method for name
Person p= new Person();
public String getName(){
//setting value in the name member
return name; }
p.setName("Ahmed");
//setter method for name
//getting value of the name member
public void setName(String n)
System.out.println(p.getName()); }}
{ name=n } }
Encapsulation
This keyword
this is a reference variable that refers to the current object.
Encapsulation: Advantages
The fields of a class can be made read-only or write-only.
A class can have total control over what is stored in its fields
Department Student
Composition VS Aggregation
Aggregation: one object has a reference to another object, but the
contained object can exist independently of the containing object.
The containing object does not own the contained objects, and the
contained objects can belong to multiple containing objects.
For example, a university has many departments, and each department
has many professors. The professors can exist independently of the
department, and they can also belong to other departments.
The Car class has a composition relationship with the Engine class:
→ Car class owns an instance of the Engine class.
→ The Engine object should be created within the constructor of the Car
class, because its lifecycle is tied to the lifecycle of the Car object.
Nourchene OUERHANI 166
Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL
The Library class has an aggregation relationship with the Book class:
→ The Library class contains a reference to one or more instances of the
Book class, but does not own them.
→ The Book objects are just passed into the constructor of the Library
class, and their lifecycle is not tied to the lifecycle of the Library object.
Nourchene OUERHANI 167
Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL
COURSERA
https://www.coursera.org/learn/java-programming
Deadline
Inheritance
● One of the crux concepts of Object-Oriented Programming
● Mechanism in which one class acquires the properties of another
class.
Inheritance: Types
There are five types of inheritance:
ce
nc
ce
ce
an
ce
ta
an
an
it
an
ri
er
t
he
t
ri
t
nh
ri
ri
he
he
In
he
lI
In
ca
l
In
ve
In
e
hi
d
pl
le
le
rc
ri
ti
ti
ng
yb
ra
ul
ul
ie
Si
H
H
1 2 3 4 5
Inheritance: Types
1. Single Inheritance 2. Multilevel Inheritance
A single subclass extends from a A subclass extends from a
single superclass. superclass and then the same
subclass acts as a superclass for
another class. Class A
Class A
Class B
Class B
Class C
Nourchene OUERHANI 172
Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL
Inheritance: Types
3. Hierarchical Inheritance 4. Multiple Inheritance
Multiple subclasses extend from A single subclass extends from
a single superclass. multiple superclasses.
Class A Class A
Inheritance: Types
Class A
5. Hybrid Inheritance
A combination of two or more Class B Class C
types of inheritance.
Class D
void eat(){System.out.println("eating...");} }
void meow(){System.out.println("meowing...");} }
class TestInheritance{
c.meow();
c.eat(); }}
Example:
If A and B classes have the same method and you call it from child class
object, there will be ambiguity to call the method of A or B class.
Since compile-time errors are better than runtime errors, Java renders
compile-time error if you inherit 2 classes. So whether you have same
method or different, there will be compile time error.
Lorem ipsum
tempus
notify() notifyAll()
Object Class
Methods
Lorem ipsum
toString() hashCode()
tempus
equals() finalize()
class Animal{
protected String color="white"; } class TestSuper1{
super.eat();
bark(); }}
public Animal(){System.out.println("animal
class TestSuper3{
is created");}}
public static void
class Dog extends Animal{
main(String args[]){
public Dog(){
Dog d=new Dog();
super();
}}
System.out.println("dog is created");
}}
Emp
class Emp extends Person{
e1=newEmp(1,"ankit",45000);
private float salary;
public Emp(int id,String name,float salary){ e1.display();
super(id,name);//reusing parent constructor
}}
this.salary=salary; }
public void display(){System.out.println(id+"
"+name+" "+salary);}}
Inheritance:
● Code reuse is the most important benefit of inheritance because
subclasses inherits the variables and methods of superclass.
● Private member inheritance: A subclass does not inherit the
private members of its parent class. However, if the superclass has
public or protected methods(like getters and setters) for accessing
its private fields, these can also be used by the subclass.
● Superclass members with default access is accessible to subclass
ONLY if they are in same package.
● Superclass constructors are not inherited by subclass.
Inheritance:
● We can create an instance of subclass and then assign it to
superclass variable, this is called upcasting.
Cat c = new Cat(); //subclass instance
Animal a = c; //upcasting, it's fine since Cat is also an Animal
Polymorphism
● The term polymorphism from the Greek means the ability to take
several forms
➔ Polymorphism means "many forms", the same entity (method or
operator or object) can perform different operations in different
scenarios.
● Inheritance lets us inherit attributes and methods from another
class. Polymorphism uses those methods to perform different tasks.
This allows us to perform a single action in different ways.
● An entity is polymorphic if at runtime it can refer to different class
instances.
Polymorphism
class Animal {
public void animalSound() {
System.out.println("The animal makes a sound");
}}
Polymorphism
We can achieve polymorphism in OOP using the following ways:
polymorphism
3. Operator Overloading
Polymorphism: Overriding
During inheritance in Java, if the same method is present in both the
superclass and the subclass. Then, the method in the subclass
overrides the same method in the superclass.
In this case, the same method will perform one operation in the
superclass and another operation in the subclass.
Polymorphism: Overriding
Polymorphism: Overloading
Polymorphism: Overloading
The method demo() is overloaded 3 times: first method has 1 int parameter,
second method has 2 int parameters and third one is having double parameter.
class InnerClass {
private int y = 5;
}
}
// Outputs 15 (5 + 10)
// Outputs 5
Nourchene OUERHANI 203
Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL
class Main {
public static void main(String[] args) {
Cat cat = new Cat(); // Create a Cat object
cat.animalSound();
cat.sleep();}
}
● An abstract class outlines the methods but not necessarily implements all of
them.
● If a child class does not implement all the abstract methods of an abstract
parent class, then the child class must be declared abstract as well.
● Since abstract class allows concrete methods as well, it does not provide 100%
abstraction.
Abstraction: Interface
Interface looks like a class but it is not a class.
An interface can have methods and variables just like the class.
The methods declared in an interface are public abstract by default.
The variables declared in an interface are public static final by default.
// interface
interface Animal {
void animalSound(); // interface method (does not have a body)
void run(); // interface method (does not have a body)
}
Abstraction: Interface
With the addition of default methods in Java 8, an interface can now
provide a default implementation for a method using the default
keyword.
// interface
interface Animal {
default void animalSound(){
System.out.println(“Making sound”);//default method having a
//default code
};
}
Abstraction: Interface
To access the interface methods, the interface must be "implemented" (kinda like
inherited) by another class with the implements keyword (instead of extends).
// Interface
interface Animal {
void animalSound(); // interface method (does not have a body)
void sleep(); // interface method (does not have a body)}
// Cat "implements" the Animal interface
class Cat implements Animal {
public void animalSound() {
// The body of animalSound() is provided here
System.out.println("The cat says: meow meow");
}
public void sleep() {
// The body of sleep() is provided here
System.out.println("Zzz");}}
class Main {
public static void main(String[] args) {
Cat cat= new Cat(); // Create a Cat object
cat.animalSound();
cat.sleep();}}
Abstraction: Interface
● Like abstract classes, interfaces cannot be used to create
objects
● Interface methods do not have a body - the body is provided
by the "implement" class
● When implementing an interface, all of its methods must be
overridden.
● An interface cannot contain a constructor.
Abstraction: Interface
Why And When To Use Interfaces?
1) To achieve security - hide certain details and only show the
important details of an object (interface).
2) Java does not support "multiple inheritance" (a class can only
inherit from one superclass)
→ However, it can be achieved with interfaces, because the class can
implement multiple interfaces.
Note: To implement multiple interfaces, separate them with a
comma.
Abstraction: Interface
interface FirstInterface {
void firstMethod(); // interface method
}
interface SecondInterface {
void secondMethod(); // interface method
}
class Main {
public static void main(String[] args) {
DemoClass myObj = new DemoClass();
myObj.firstMethod();
myObj.secondMethod();}
}