0% found this document useful (0 votes)
24 views217 pages

OOP JAVA Master

Uploaded by

sgdenimhouse
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views217 pages

OOP JAVA Master

Uploaded by

sgdenimhouse
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 217

Object Oriented

Programming (OOP)
Teaching Assistant: Nourchene OUERHANI
([email protected])

2023-2024 Master DS-AI-HT & DS-AI-I4.0


Object Oriented Programming (OOP) Objectives

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

Struct firstName readDirector()


Director lastName displayDirector()
phonenNumber calcSalary()
faxNumber
officeNumber
salary
service

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

class Engineer class Technician class Director

hireDate faxNumber
hireDate
specialty officeNumber
specialty
diplomaList service

calSalEngineer() calSalTechnician() calSalDirector()

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

OAK Green Java coffee


Nourchene OUERHANI 13
Object Oriented Programming (OOP) Object-oriented programming Introduction

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

Popular Projects on Java

NASA World Wind

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.

2. Object-Oriented: it allows for the creation of reusable code modules in the


form of objects.

3. Garbage Collection: Java provides automatic memory management through


its garbage collection feature. This means that developers do not need to
manually allocate and deallocate memory, which can help to reduce the risk
of memory leaks and other memory-related issues.

4. Large Community: Java has a large and active community of developers,


which means that there are many resources available for learning and support.

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.

2. Rich Ecosystem: Java has a large and vibrant ecosystem of libraries,


frameworks, and tools that can be used to extend and enhance the language.
This includes popular frameworks like Spring and Hibernate, which can help to
simplify development and streamline the development process.

3. Performance: While Java is not as fast as low-level languages like C or C++, it is


still a high-performance language that can be used to build complex
applications that require fast processing times.

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.

2. Memory Consumption: While Java's automatic memory management can be


an advantage, it can also lead to high memory consumption. This can be a
problem for devices with limited memory resources.

3. Complexity: Java is a complex programming language with many advanced


features and concepts, which can make it difficult for beginners to learn.

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...).

→ The IDE we are going to use is: Eclipse.

Nourchene OUERHANI 28
Object Oriented Programming (OOP) Object-oriented programming Introduction

Java Environment: ECLIPSE

● Eclipse is an extensible, universal and versatile open source


integrated development environment for creating development
projects that implement any programming language.
● Eclipse IDE is mainly written in Java (using IBM's SWT graphics
library).
● The specificity of Eclipse IDE comes from its architecture totally
developed around the notion of plugin (in accordance with the
OSGi standard): all the functionalities of this software workshop
are developed as a plug-in.

Nourchene OUERHANI 29
Object Oriented Programming (OOP) Object-oriented programming Introduction

Java Environment: ECLIPSE

Work space Class VieW


Editor

Other Views

Console

Nourchene OUERHANI 30
Object Oriented Programming (OOP) Object-oriented programming Introduction

Java Environment: ECLIPSE


Steps to Create a Project on Eclipse
1. Open the Eclipse IDE, you will be asked to
choose the workspace in which you find
the projects.
2. Type the path of the directory created on
the desktop. Otherwise, Eclipse will create
it.
3. Close the welcome window that appears:
We are in the workspace.
4. Create a new Java project. To do this, press
File → New → Java Project
5. The following window will appear: Type the
name of the project as indicated.
6. Keep the default settings, and press Finish.
Nourchene OUERHANI 31
Object Oriented Programming (OOP) Object-oriented programming Introduction

Java Environment: ECLIPSE


Steps to Create a Project on Eclipse
6. In the workspace, under the Package Explorer tab, we can see that the
project is created, and that it already contains a src directory (which must
contain all the source files created), and JRE System Library, which is used
to compile your code.
7. Create a package under the src directory: right-click on src, and choose
New -> Package.
8. Name the package.
9. Create a class: Right-click on the package which must contain the class
then New -> Class.
10. Name the class.
11. Ability to automatically generate the main method by checking the
public static void main(String[]args) box.
Nourchene OUERHANI 32
Object Oriented Programming (OOP) Object-oriented programming Introduction

Java Environment: ECLIPSE


Steps to Create a Project on Eclipse

● NB: If the class is not defined in a package (which is not


recommended), redo the last operation from the src directory.
The generated class will appear under the chosen package.
● Double-click on it to modify its code in the editor: a skeleton of
the class is proposed. Just finish the rest of the code.
● With Eclipse, there is no need to explicitly compile the code: the
compilation is done in real time. In addition, syntax errors will be
displayed while writing the code, with suggestions for
corrections.

Nourchene OUERHANI 33
Object Oriented Programming (OOP) Object-oriented programming Introduction

Activity 1: Answer the questions


1. To distribute your application on different platforms, how many versions of
Java do you need to create?

2. A file Hello.java containing the text below:


class Hello
{ public static void main(String args[]) {
System.out.println("Hello"); }
}
Which of the following command lines are incorrect and why?

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 1: Answer the question


1. To distribute your application on different platforms, how many versions of
Java do you need to create?
2. A file Hello.java containing the text below:
public class Hello
{
public static void main(String[] args) {
System.out.println("Hello"); }
}
Which of the following command lines are incorrect and why?
1. javac Hello.java
2. java Hello.java Java is a command to run, and .java is a line source file
3. javac Hello.class Conversely, javac is a compilation command and
.class is a bytecode
4. java Hello.class No need to specify the .class extension
5. java Hello
Nourchene OUERHANI 35
Object Oriented Programming (OOP) Object-oriented programming Introduction

Activity 2:

1. Create a new Helloworld project as indicated in the previous


part.
2. Create a package named helloWorldPack, containing a
Helloworld class that contains a main method.
3. In the main method, write " System.out.println("Hello World!");
4. Run your program by clicking directly on the icon.
5. The display will appear at the bottom, under the Console tab.

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:

4. Select the Arguments tab


5. In Program arguments: type
your name.
6. Then click on Run.
7. In the console window the
display
Hello your_name!

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

JAVA language syntax


1. Code Example
2. Print Method
3. Java Comments
4. Java Variables
5. Java Operators
6. Java Control Statements
7. Java Array
Nourchene OUERHANI
Object Oriented Programming (OOP) JAVA language syntax

Code Example
public class Hello
{
static public void main(String[] args)
{
System.out.println("Hello");
}
}

Every line of code that runs in Java


must be inside a class

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.

● Text must be wrapped inside double quotations marks "".


● To print numbers we don't put them inside double quotes:
System.out.print(3);
● There is also a print() method, that is similar to println().
System.out.print(3);
● The only difference is that it does not insert a new line at the end of
the output.
Nourchene OUERHANI 45
Object Oriented Programming (OOP) JAVA language syntax

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.

// Single-line comments start with two forward slashes (//).


System.out.println("Hello");

System.out.println("Hello");// This is another single-line comment

/* Multi-line comments start with /* and ends with */


Any text between /* and */ will be ignored by Java.*/
System.out.println("Hello");
Nourchene OUERHANI 46
Object Oriented Programming (OOP) JAVA language syntax

Java Variables: Declaring


Variables are containers for storing data values.
To create a variable, we must specify the type and assign it a value:
type variableName = value;
or
type variableName;
variableName = value;
String firstName = "Nour";
System.out.println(firstName );

int number;
number= 15;
System.out.println(number);

Nourchene OUERHANI 47
Object Oriented Programming (OOP) JAVA language syntax

Java Variables: Declare multiple variables


To declare multiple variables of the same type: use a comma-separated
list.

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

Java Variables: One value to multiple variables


Assign the same value to multiple variables in one line.

int x, y, z;
x = y = z = 50;
System.out.println(x + y + z);

Nourchene OUERHANI 49
Object Oriented Programming (OOP) JAVA language syntax

Java Variables: Identifiers


Identifiers are the names of local variables, instance and class variables,
and labels, but also the names for classes, packages, modules and
methods.
● All identifiers should begin with a letter, a currency symbol ($) or
an underscore (_).
● According to the convention, Names should start with a lowercase
letter and it cannot contain whitespace
● The first character of identifiers can be followed by any combination
of letters, digits, currency symbols and the underscore. The
underscore is not recommended for the names of variables.

Nourchene OUERHANI 50
Object Oriented Programming (OOP) JAVA language syntax

Java Variables: Identifiers

● Constants (static final attributes and enums) should be in all


Uppercase letters: PI, HEIGHT
● Most importantly identifiers are case-sensitive (firstName ≠
FirstName ≠ firstname)
● A keyword cannot be used as an identifier since it is a reserved word
and has some special meaning.

Nourchene OUERHANI 51
Object Oriented Programming (OOP) JAVA language syntax

Java Variables: Types


Data types are divided into two groups:
● Primitive data types:
○ A primitive data type specifies the size and type of variable
values, and it has no additional methods.
○ There are eight primitive data types in Java: byte, short, int,
long, float, double, boolean and char
● Non-primitive data types: String, Arrays, Classes, Interfaces, etc.
int intNumber = 5; // Integer
float floatNumber = 5.99f; // Floating point number
char charvar = 'D'; // Character
boolean boolVar = true; // Boolean
String textVar = "Hello"; // String

Nourchene OUERHANI 52
Object Oriented Programming (OOP) JAVA language syntax

Java Variables: Types


Main difference between primitive and non-primitive data types

● Primitive types are predefined in Java.


● Non-primitive types are created by the programmer and is not defined
by Java (except for String).
● Non-primitive types can be used to call methods to perform certain
operations, while primitive types cannot.
● A primitive type has always a value, while non-primitive types can be
null.

● A primitive type starts with a lowercase letter, while non-primitive


types starts with an uppercase letter.

Nourchene OUERHANI 53
Object Oriented Programming (OOP) JAVA language syntax

Java Variables: Types


There are different types of variables.
byte
● Size = 1 byte = 8 bits
● Stores whole numbers from -128 (-2^7) to 127 (2^7 - 1)
● Example: byte a = 100, byte b = -50

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

Java Variables: Types


int
● Size = 4 byte = 32 bits
● Stores whole numbers from -2,147,483,648 (-2^31) to 2,147,483,647
(2^31-1)
● Example: int a = 100000, int b = -200000

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

Java Variables: Types


float double
● Size= 4 bytes = 32 bits ● Size= 8 bytes = 64 bits
● Stores fractional numbers. ● Stores fractional numbers.
● Sufficient for storing 6 to 7 ● Sufficient for storing 15 decimal
decimal digits digits
● Default value is 0.0f ● Default value is 0.0d
● Example: float f1 = 234.5f ● Example: double d = 45.5d

Nourchene OUERHANI 56
Object Oriented Programming (OOP) JAVA language syntax

Java Variables: Types


boolean
● Size = 1 byte
● There are only two possible values: true and false
● Default value is false
● Example: boolean one = true

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

Java Variables: Java Typecasting


Type casting is when you assign a value of one primitive data type to
another type.
In Java, there are two types of casting:
● Widening Casting: Implicit Type Casting
○ Done automatically when passing a smaller size type to a larger
size type:
byte -> short -> char -> int -> long -> float -> double
● Narrowing Casting: Explicit Type Casting
○ Converting a larger type to a smaller size type.
double -> float -> long -> int -> char -> short -> byte
○ Must be done manually by placing the type in parentheses in
front of the value
Nourchene OUERHANI 58
Object Oriented Programming (OOP) JAVA language syntax

Java Variables: Java Typecasting


Widening Casting Narrowing Casting

public class Narrowing{


public class Widening{
public static void main(String[] args){
public static void main(String[] args){
float f=10.5f;
int a=10;
//int a=f;//Compile time error
float f=a;
int a=(int)f;
System.out.println(a);
System.out.println(f);
System.out.println(f);
System.out.println(a);
}}
}}

Nourchene OUERHANI 59
Object Oriented Programming (OOP) JAVA language syntax

Java Variables: String


● Stores text, such as "Hello".
● String values are surrounded by double quotes
● A String in Java is an object, which contain methods that can
perform certain operations on strings:
○ The length of a string can be found with the length() method.
○ toUpperCase() and toLowerCase()
○ The indexOf() method returns the index (the position) of the first
occurrence of a specified text in a string (including whitespace).

Nourchene OUERHANI 60
Object Oriented Programming (OOP) JAVA language syntax

Java Variables: String


String txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
System.out.println("The length of the txt string is: " + txt.length());

String txt = "Hello World";


System.out.println(txt.toUpperCase()); // Outputs "HELLO WORLD"
System.out.println(txt.toLowerCase()); // Outputs "hello world"

String txt = "Please locate where 'locate' occurs!";


System.out.println(txt.indexOf("locate")); // Outputs 7

Nourchene OUERHANI 61
Object Oriented Programming (OOP) JAVA language syntax

Java Variables: String Concatenation


The + operator can be used between strings to combine them.

→ This is called concatenation

We can also use the concat() method to concatenate two strings.

String firstName = "Nourchene";


String lastName = "Ouerhani";
System.out.println(firstName + " " + lastName);

String firstName = "Nourchene ";


String lastName = "Ouerhani";
System.out.println(firstName.concat(lastName));

Nourchene OUERHANI 62
Object Oriented Programming (OOP) JAVA language syntax

Java Variables: Type conversion from int to String


valueOf() method of the Java String class is used to convert the int type
variable into a string.
class Main {
public static void main(String[] args) {
// create int type variable
int num = 10;
System.out.println("The integer value is: " + num);

// converts int to string type


String data = String.valueOf(num);
System.out.println("The string value is: " + data);
}}

Nourchene OUERHANI 63
Object Oriented Programming (OOP) JAVA language syntax

Java Variables: Type conversion from String to int


parseInt() method of the Java Integer class is used to convert a string
type variable into an int variable.
class Main {
public static void main(String[] args) {
// create string type variable
String data = "10";
System.out.println("The string value is: " + data);

// convert string variable to int


int num = Integer.parseInt(data);
System.out.println("The integer value is: " + num);
}}

Nourchene OUERHANI 64
Object Oriented Programming (OOP) JAVA language syntax

Java Variables: String Special Characters


● Because strings must be written within quotes, Java will misunderstand
string containing double quotes, and generate an error.
● The solution to avoid this problem, is to use the backslash escape
character.
● The backslash (\) escape character turns special characters into string
characters.

String text = "We are students at "Pristini" school of AI.";

String text = "We are students at \"Pristini\" school of AI.";


String text = "I\'m fine.";
String text = "The character \\ is called backslash.";

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

3. Static variable: A variable that is declared as static.

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

Java User Input


The Scanner class is used to get user input, and it is found in the
java.util package.

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

Java User Input


Method Description

nextBoolean() Reads a boolean value from the user


nextByte() Reads a byte value from the user
nextDouble() Reads a double value from the user
nextFloat() Reads a float value from the user
nextInt() Reads a int value from the user
nextLine() Reads a String value from the user
nextLong() Reads a long value from the user
nextShort() Reads a short value from the user

Nourchene OUERHANI 70
Object Oriented Programming (OOP) JAVA language syntax

Java Arithmetic operators


Operator Name Description Example

+ Addition Adds together two values x + y


- Subtraction Subtracts one value from another x - y
* Multiplication Multiplies two values x * y
/ Division Divides one value by another x / y
% Modulus Returns the division remainder x % y
++ Increment Increases the value of a variable by 1 ++x
-- Decrement Decreases the value of a variable by 1 --x

Nourchene OUERHANI 71
Object Oriented Programming (OOP) JAVA language syntax

Java Assignment operators


Operator Example Same As

= 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

^= x ^= 3 x = x ^ 3

>>= x >>= 3 x = x >> 3

<<= x <<= 3 x = x << 3


Object Oriented Programming (OOP) JAVA language syntax

Java comparison operators

Operator Name Example


== Equal to x == y
!= Not equal x != y
> Greater than x > y
< Less than x < y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y

Nourchene OUERHANI 73
Object Oriented Programming (OOP) JAVA language syntax

Java logical operators

Operator Name Description Example


&& Logical and Returns true if both x < 5 && x < 10
statements are true
|| Logical or Returns true if one of x < 5 || x < 4
the statements is
true
! Logical not Reverse the result, !(x < 5 && x < 10)
returns false if the
result is true

Nourchene OUERHANI 74
Object Oriented Programming (OOP) JAVA language syntax

Java Control Statements: Java Conditions


Java has the following conditional statements:
● Use if to specify a block of code to be executed, if a specified
condition is true
● Use else to specify a block of code to be executed, if the same
condition is false
● Use else if to specify a new condition to test, if the first condition is
false
● Use switch to specify many alternative blocks of code to be executed

Nourchene OUERHANI 75
Object Oriented Programming (OOP) JAVA language syntax

Java Control Statements: Java Conditions

Here are some condition examples


● Less than: a < b
● Less than or equal to: a <= b
● Greater than: a > b
● Greater than or equal to: a >= b
● Equal to a == b
● Not Equal to: a != b

Nourchene OUERHANI 76
Object Oriented Programming (OOP) JAVA language syntax

Java Control Statements: if Statement

Use the if statement to specify a block of Java code to be executed if a


condition is true.

if (condition) {
// block of code to be executed if the condition is true
}

int time = 22;


if (time > 10) {
System.out.println("Good evening.");}

Nourchene OUERHANI 77
Object Oriented Programming (OOP) JAVA language syntax

Java Control Statements: else Statement


Use the else statement to specify a block of code to be executed if the
condition is false.
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}

int time = 22;


if (time < 10) {
System.out.println("Good morning.");}
else {
System.out.println("Good evening.");}

Nourchene OUERHANI 78
Object Oriented Programming (OOP) JAVA language syntax

Java Control Statements: else if Statement


The else if statement to specify a new condition if the first condition is
false.

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

Java Control Statements: else if Statement

int time = 22;


if (time < 10) {
System.out.println("Good morning.");
} else if (time < 20) {
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
}

Nourchene OUERHANI 80
Object Oriented Programming (OOP) JAVA language syntax

Java Control Statements: Short Hand If...Else


There is also a short-hand if-else, which is known as the ternary operator
because it consists of three operands.

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:

variable = (condition) ? expressionTrue : expressionFalse;

Nourchene OUERHANI 81
Object Oriented Programming (OOP) JAVA language syntax

Java Control Statements: Short Hand If...Else


int time = 20;
if (time < 18) {
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
}

int time = 20;


String result = (time < 18) ? "Good day." : "Good evening.";
System.out.println(result);

Nourchene OUERHANI 82
Object Oriented Programming (OOP) JAVA language syntax

Java Control Statements: Switch


Instead of writing many if..else statements, you can use the switch
statement.
The switch statement selects one of many code blocks to be executed:

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

Java Control Statements: Switch


● The value of the expression is compared with the values of each case.
● If there is a match, the associated block of code is executed.
● The break keyword is optional
○ When Java reaches a break keyword, it breaks out of the switch
block.
○ This will stop the execution of more code and case testing inside
the block.
○ When a match is found, and the job is done, it's time for a break.
There is no need for more testing.
● The default keyword is optional and specifies some code to run if
there is no case match.

Nourchene OUERHANI 84
Object Oriented Programming (OOP) JAVA language syntax

Java Control Statements: Switch


int day = 4;
switch (day) {
case 6:
System.out.println("Today is Saturday");
break;
case 7:
System.out.println("Today is Sunday");
break;
default:
System.out.println("Looking forward to the Weekend");
}

Nourchene OUERHANI 85
Object Oriented Programming (OOP) JAVA language syntax

Java Control Statements: While loop


The while loop loops through a block of code as long as a specified
condition is true.

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

Java Control Statements: Do/While Loop


The do/while loop is a variant of the while loop. This loop will execute the
code block once, before checking if the condition is true, then it will
repeat the loop as long as the condition is true.

do {
// code block to be executed
}
while (condition);

Nourchene OUERHANI 87
Object Oriented Programming (OOP) JAVA language syntax

Java Control Statements: Do/While Loop


The example below uses a do/while loop. The loop will always be
executed at least once, even if the condition is false, because the code
block is executed before the condition is tested.
int i = 0;

do {
System.out.println(i);
i++;
}

while (i < 5);

Nourchene OUERHANI 88
Object Oriented Programming (OOP) JAVA language syntax

Java Control Statements: for Loop


When you know exactly how many times you want to loop through a
block of code, use the for loop instead of a while loop.
for (initialization; test; update){
// code block to be executed
}

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

Java Control Statements: for Loop


for (int i = 0; i < 5; i++) {
System.out.println(i);
}

for (int i = 0; i <= 10; i = i + 2) {


System.out.println(i);
}

Nourchene OUERHANI 90
Object Oriented Programming (OOP) JAVA language syntax

Java Control Statements: Nested Loop


It is also possible to place a loop inside another loop. This is called a
nested loop.

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

Java Control Statements: for-each Loop


There is also a "for-each" loop, which is used exclusively to loop through
elements in an array.

for (type variableName : arrayName) {


// code block to be executed
}

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

Java Control Statements: Break


The break statement was used to "jump out" of a switch statement.
The break statement can also be used to jump out of a loop.
This example stops the loop when i is equal to 4:

for (int i = 0; i < 10; i++) {


if (i == 4) {
break;
}
System.out.println(i);
}
Nourchene OUERHANI 93
Object Oriented Programming (OOP) JAVA language syntax

Java Control Statements: Break


The break statement was used to "jump out" of a switch statement.
The break statement can also be used to jump out of a loop.
This example stops the loop when i is equal to 4:

for (int i = 0; i < 10; i++) {


if (i == 4) {
Use while loop
break;
}
System.out.println(i);
}
Nourchene OUERHANI 94
Object Oriented Programming (OOP) JAVA language syntax

Java Control Statements: Continue


The continue statement breaks one iteration (in the loop), if a specified
condition occurs, and continues with the next iteration in the loop.

This example skips the value of 4:

for (int i = 0; i < 10; i++) {


if (i == 4) {
continue;
}
System.out.println(i);
}
Nourchene OUERHANI 95
Object Oriented Programming (OOP) JAVA language syntax

Java Control Statements: Continue


The continue statement breaks one iteration (in the loop), if a specified
condition occurs, and continues with the next iteration in the loop.

This example skips the value of 4:

for (int i = 0; i < 10; i++) {


if (i == 4) {
Use while loop
continue;
}
System.out.println(i);
}
Nourchene OUERHANI 96
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;

We have now declared a variable that holds an array of strings. To insert


values to it, you can place the values in a comma-separated list, inside
curly braces.
String[] cars = {"Renault", "BMW", "Ford", "Mazda"};
int[] setNumbers= {10, 20, 30, 40};

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.

String[] cars = {"Renault", "BMW", "Ford", "Mazda"};


System.out.println(cars[0]);

Nourchene OUERHANI 99
Object Oriented Programming (OOP) JAVA language syntax

Java Arrays
Use the index number to modify the value of a particular element.

String[] cars = {"Renault", "BMW", "Ford", "Mazda"};


cars[0] = "Opel";
System.out.println(cars[0]);

Use the length property to determine how many elements an array


contains.

String[] cars = {"Renault", "BMW", "Ford", "Mazda"};


System.out.println(cars.length);

Nourchene OUERHANI 100


Object Oriented Programming (OOP) JAVA language syntax

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.

String[] cars = {"Renault", "BMW", "Ford", "Mazda"};


for (int i = 0; i < cars.length; i++) {
System.out.println(cars[i]); //outputs all elements in the cars array
}

Nourchene OUERHANI 101


Object Oriented Programming (OOP) JAVA language syntax

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.

Comparing for loop to for-each loop


● Easier to write,
● Does not require a counter (using the length property)
● More readable.

Nourchene OUERHANI 102


Object Oriented Programming (OOP) JAVA language syntax

Java Arrays: Multidimensional Arrays


A multidimensional array is an array of arrays.
To create a two-dimensional array, add each array within its own set of
curly braces:

int[][] setNumbers= { {1, 2, 3, 4}, {5, 6, 7} }; //setNumbers


is an array with two arrays as its elements.

To access the elements of the setNumbers array, specify two indexes:


● One for the array
● One for the element inside that array

Nourchene OUERHANI 103


Object Oriented Programming (OOP) JAVA language syntax

Java Arrays: Multidimensional Arrays


This example accesses the third element (2) in the second array (1) of
setNumbers:

int[][] setNumbers= { {1, 2, 3, 4}, {5, 6, 7} };


int x = setNumbers[1][2];
System.out.println(x); // Outputs 7

Nourchene OUERHANI 104


Object Oriented Programming (OOP) JAVA language syntax

Java Arrays: Multidimensional Arrays


To get the elements of a two-dimensional array, we use a for loop inside
another for loop :

public class Main {


public static void main(String[] args) {
int[][] setNumbers= { {1, 2, 3, 4}, {5, 6, 7} };
for (int i = 0; i < setNumbers.length; ++i) {
for(int j = 0; j < setNumbers[i].length; ++j) {
System.out.println(setNumbers[i][j]);
}}}}

Nourchene OUERHANI 105


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

OOP Fundamentals: JAVA OOPL

1. Class
2. Object
3. Inheritance and composition
4. Abstraction
5. Interface

Nourchene OUERHANI 107


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

Class: Naming Convention


● It should start with the uppercase letter.
● It should be a noun such as Color, Button, System, Thread,
etc.
● Use appropriate words, instead of acronyms.

Nourchene OUERHANI 108


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

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

Nourchene OUERHANI 109


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

Class: Create a class


To create a class, use the keyword class.
class className{
//attributes
//methods
}

Let’s create a class named "Person" with a variable age:

public class Person{


int age = 50;
}

Nourchene OUERHANI 110


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

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).

➔ The banking system is an intangible object.

Nourchene OUERHANI 111


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

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.

● Some objects may have both physical and logical aspects:


○ A book is a physical object that can be held and read, but the ideas and
concepts contained within the book are logical objects.
○ Computer program is a logical object that exists as a series of instructions
and code, but it requires a physical device to run on.
Nourchene OUERHANI 112
Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

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

Nourchene OUERHANI 115


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

Class VS Object

Class
Object

Nourchene OUERHANI 116


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

Object
Syntax
This statement has three parts:
ClassName objectName = new ClassName();
1. Declaration
2. Instantiation
OR 3. Initialization

ClassName objectName;

objName= new ClassName();

Nourchene OUERHANI 117


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

Object: Example

public class Person{


public class Person{
int a = 50;
int a = 50;
public static void main(String[] args)
public static void main(String[] args)
{ Person myObject;
{ Person myObject = new Person();
myObject = new Person();
System.out.println(myObject.a);}}
System.out.println(myObject.a);}}

Nourchene OUERHANI 118


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

Object: Declaring a Variable to Refer to an Object


A reference variable can be declared on its own line.
For example: Person myObject;
➔ Value will be undetermined until an object is actually created and
assigned to it.
➔ Declaring a reference variable does not create an object.
➔ Use the new operator
A variable in this state can be illustrated as follows:
● Variable name: myObject
● A reference pointing to nothing
Nourchene OUERHANI 119
Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

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:

Person object = new Person(50);


The reference returned by the new operator does not have to be assigned to a
variable. It can also be used directly in an expression. For example:

int a = new Person().a;


Nourchene OUERHANI 120
Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

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);
}

Nourchene OUERHANI 121


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

Object
A Person object

personObject a 50

Nourchene OUERHANI 122


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

Object
public class Person{

int a = 50;

public static void main(String[] args) {

Person myObj1 = new Person(); // Object 1


Person myObj2 = new Person(); // Object 2
System.out.println(myObj1.a);

System.out.println(myObj2.a);

Nourchene OUERHANI 123


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

Object: Using Multiple Classes


This is often used for better organization of classes:

● Classes that have all the attributes and methods


● Class that holds the main() method (code to be executed).

The name of the java file should match the class name.

Let’s create two files in the same package

● Main.java
● Person.java

Nourchene OUERHANI 124


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

Object: Using Multiple Classes

Person.java Main.java

public class Person{ public class Main {


int a = 50; public static void main(String[] args) {

} Person myObj1 = new Person(); // Object 1

Person myObj2 = new Person(); // Object 2

System.out.println(myObj1.a);

System.out.println(myObj2.a);

}}

Nourchene OUERHANI 125


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

Attributes
We used the term "variable" for x in the Person class.

➔ It is an attribute of the class.


➔ class attributes are variables within a class:

Let’s create a class called "Person" with two attributes: age and height:
public class Person {
int age = 50;
float height = 180;
}

Nourchene OUERHANI 126


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

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:

public class Person {


int age = 50;

public static void main(String[] args) {


Person myObj = new Person();
System.out.println(myObj.age);}}

Nourchene OUERHANI 127


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

Attributes: Modification
Let’s set the value of age to 32: Let’s override the value of age:

public class Person { public class Person {


int age; int age=50;

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);}}

Nourchene OUERHANI 128


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

Attributes: Modification
Let’s set the value of age to 32: Let’s override the value of age:

public class Person { public class Person {


int age; int age=50;

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);}}

How to disable overriding existing values?

Nourchene OUERHANI 129


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

Attributes: Modification
Let’s set the value of age to 32: Let’s override the value of age:

public class Person { public class Person {


int age; int age=50;

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);}}

How to disable overriding existing values?


➔ Declare the attribute as final

Nourchene OUERHANI 130


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

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.

DRY Principle in Java?


Nourchene OUERHANI 131
Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

Methods: Naming Convention

● Method should start with lowercase letter.


● Java follows camelcase syntax for naming the class, interface,
method, and variable.
➔ If the name is combined with two words, the second word
will start with uppercase letter always such as
performTask(), getName()

Nourchene OUERHANI 132


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

Methods Method
Signature

Access Return Method Parameter


specifier type name List

public double sum (double x, double y) Method


Head
{
//Method body
}

Nourchene OUERHANI 133


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

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:

● public: The method is accessible by all classes in our application.

● private: The method is accessible only in the classes in which it is defined.

● protected: The method is accessible within the same package or


subclasses in a different package.

● 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.

Nourchene OUERHANI 134


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

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.

Parameter List: It is the list of parameters separated by a comma and enclosed in


the pair of parentheses. It contains the data type and variable name. If the method
has no parameter, left the parentheses blank.

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

Methods: Method overloading


With method overloading, multiple methods can have the same name
with different parameters:

int myMethod(int x)
float myMethod(float x)
double myMethod(double x, double y)

Nourchene OUERHANI 136


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

Methods: Method overloading


static int sum(int x, int y) {
static int sumInt(int x, int y) { return x + y;
return x + y; }
}
static double sum(double x, double y)
static double sumDouble(double x, double y) {
{ return x + y;
return x + y; }
}
public static void main(String[] args)
public static void main(String[] args) { {
int sum1 = sumInt(8, 5); int sum1 = sum(8, 5);
double sum2 = sumDouble(4.3, 6.26); double sum2 = sum(4.3, 6.26);
System.out.println("int: " + sum1); System.out.println("int: " + sum1);
System.out.println("double: " + sum2); System.out.println("double: " +
} sum2);
}

Nourchene OUERHANI 137


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

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.

Nourchene OUERHANI 138


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

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.

● What happens if the main() method is written without String[]


args?
➔ The program will compile, but not run, because JVM will not
recognize the main() method.
➔ NB: JVM always looks for the main() method with a string type array
as a parameter.
Nourchene OUERHANI 139
Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

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.

Rules for creating Java constructor

1. Constructor name must be the same as its class name


2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, or synchronized

Nourchene OUERHANI 140


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

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(){}

Nourchene OUERHANI 141


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

Constructor: Types
Default constructor (no-arg constructor)

public class Person {


int age;
String name;
public static void main(String[] args) {
Person myObj = new Person();
System.out.println(myObj.age);
System.out.println(myObj.name);}}

Nourchene OUERHANI 142


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

Constructor: Types
Parameterized Constructors

● A constructor which has a specific number of parameters is called a


parameterized constructor.
● The parameterized constructor is used to provide different values to
distinct objects. However, you can provide the same values also.

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);}}

Nourchene OUERHANI 144


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

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

class name. not be same as the class name.


The Java compiler provides a default constructor The method is not provided by the
compiler in any case.
if you don't have any constructor in a class.

A constructor is used to initialize the state of A method is used to expose the


an object. behavior of an object.

A constructor must not have a return type. A method must have a return type

Nourchene OUERHANI 145


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

Modifiers

Modifiers are divided into two groups:

● Access Modifiers: controls the access level.


● Non-Access Modifiers: do not control access level, but
provides other functionality.

Nourchene OUERHANI 146


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

Modifiers: Access Modifiers


For classes, public or default modifiers are used:
● public: The class is accessible by any other class.
● default: The class is only accessible by classes in the same package.
This is used when you don't specify a modifier.
For attributes, methods and constructors, you can use the one of the
following:
● public: The code is accessible for all classes.
● private: The code is only accessible within the declared class
● default: The code is only accessible in the same package.
● protected: The code is accessible in the same package and
subclasses.

Nourchene OUERHANI 147


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

Modifiers: Access Modifiers

Private Class In Java?

Nourchene OUERHANI 148


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

Modifiers: Access Modifiers

Private Class In Java


Yes, we can declare a class as private but these classes can be only inner
or nested classes.
We can’t a top-level class as private because it would be completely
useless as nothing would have access to it.

Nourchene OUERHANI 149


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

Modifiers: Non-Access Modifiers

For classes, final or abstract modifiers are used:


● final: The class cannot be inherited by other classes
● abstract:The class cannot be used to create objects
For attributes and methods, you can use the one of the following:
● final: Attributes and methods cannot be overridden/modified
● static: Attributes and methods belongs to the class, rather than an
object
● abstract: Can only be used in an abstract class, and can only be used
on methods.

Nourchene OUERHANI 150


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

Modifiers: Non-Access Modifiers

static Class In Java?

Nourchene OUERHANI 151


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

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 } }

Nourchene OUERHANI 153


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 name)
System.out.println(p.getName()); }}
{ this.name=name } }

Nourchene OUERHANI 154


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

This keyword
this is a reference variable that refers to the current object.

● this can be used to refer current class instance variable.


● this can be used to invoke current class method
● this() can be used to invoke current class constructor.
● this can be passed as an argument in the method call.
● this can be passed as argument in the constructor call.

Nourchene OUERHANI 155


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

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

//Read-only class //Write-only class

public class Student{ public class Student{

private String university="PRISTINI"; private String university="PRISTINI";

//getter method for university //getter method for university

public String getUniversity(){ public void setUniversity(String university){

return university;}} this.university=university;}}

Nourchene OUERHANI 156


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

Association, Composition and Aggregation in Java


Association
Association is a relation between two separate classes which establishes through
their Objects. Association can be one-to-one, one-to-many, many-to-one,
many-to-many. In Object-Oriented programming, an Object communicates to
another object to use functionalities and services provided by that object.
Composition and Aggregation are the two forms of association.

Nourchene OUERHANI 157


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

Association, Composition and Aggregation in Java

Nourchene OUERHANI 158


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

Association, Composition and Aggregation in Java


Example:
Two separate classes Department and Student are associated through
their Objects.
Department can have many Student, So it is a one-to-many relationship.

Department Student

departmentName: String name: String


1..*
getdepartmentName(): String getName(): String
setdepartmentName(String name): void setName(String name): void

Nourchene OUERHANI 159


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

Association, Composition and Aggregation in Java


Aggregation
It is a special form of Association where:
● It represents Has-A relationship.
● It is a unidirectional association i.e. a
one-way relationship. For example, a
College can have students but vice
versa is not possible and thus
unidirectional in nature.
● In Aggregation, both the entries can
survive individually which means
ending one entity will not affect the
other entity.

Nourchene OUERHANI 160


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

Association, Composition and Aggregation in Java


Composition
Composition is a restricted form of
Aggregation in which two entities are
highly dependent on each other.
● It represents part-of relationship.
● In composition, both entities are
dependent on each other.
● When there is a composition
between two entities, the
composed object cannot exist
without the other entity.

Nourchene OUERHANI 161


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

Association, Composition and Aggregation in Java


Composition VS Aggregation
In object-oriented programming, both composition and aggregation are
used to describe the relationship between objects. The main difference
between them is the level of ownership and the lifecycle of the contained
objects:

Composition: One object is composed of one or more other objects. The


containing object owns the contained objects, and the contained objects
cannot exist without the containing object.

For example, a car is composed of an engine, wheels, and other components.


The car owns these components, and they cannot exist independently
without the car.
Nourchene OUERHANI 162
Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

Association, Composition and Aggregation in Java

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.

Nourchene OUERHANI 163


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

Association, Composition and Aggregation in Java

Nourchene OUERHANI 164


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

Association, Composition and Aggregation in Java

Nourchene OUERHANI 165


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

Composition VS Aggregation in Java


Composition Java code example:
public class Engine {//Engine implementation}

public class Car {


private Engine engine;
public Car() {this.engine = new Engine();}
//Car implementation}

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

Composition VS Aggregation in Java


Aggregation Java code example:
public class Book {// Book implementation}

public class Library {


private List<Book> books;
public Library(List<Book> books) {this.books = books;}
// Library implementation}

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

Solve the problem of WEEK 2:


Programming Exercise: Finding a Gene and
Web Links

Deadline

Nourchene OUERHANI 168


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

Inheritance
● One of the crux concepts of Object-Oriented Programming
● Mechanism in which one class acquires the properties of another
class.

● Represents the IS-A relationship which is also known as a


parent-child relationship.
● A child class inherits features from a parent class.
→ Through this hierarchical process the classes share various
features, attributes, methods, etc.
● Facilitates the code reusability.

Nourchene OUERHANI 169


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

Inheritance: Terms used in Inheritance


● Sub/Child/Derived/Extended Class: The class that inherits the
other class.
● Super /Parent/Base Class: The class from where a subclass
inherits the features.
● Code reusability: All subclasses share the code that was written in
the superclass. The parent class's code can be used directly by
child classes.

Nourchene OUERHANI 170


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

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

Nourchene OUERHANI 171


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

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

Class B Class C Class B Class C

→ Java doesn't support multiple


inheritance.
Nourchene OUERHANI 173
Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

Inheritance: Types

Class A

5. Hybrid Inheritance
A combination of two or more Class B Class C
types of inheritance.

Class D

Nourchene OUERHANI 174


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

Inheritance: Java Syntax


The extends keyword indicates that you are making a new class that
derives from an existing class.
The meaning of "extends" is to increase the functionality.

class Subclass-name extends Superclass-name

//methods and fields

Nourchene OUERHANI 175


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

Inheritance: Java Syntax


1. Single Inheritance
class Animal{

void eat(){System.out.println("eating...");} }

class Cat extends Animal{

void meow(){System.out.println("meowing...");} }

class TestInheritance{

public static void main(String args[]){

Cat c=new Cat();

c.meow();

c.eat(); }}

Nourchene OUERHANI 176


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

Inheritance: Java Syntax


2. Multilevel Inheritance
class Animal{
void eat(){
System.out.println("eating...");} class TestInheritance2{
}
public static void main(String args[]){
class Cat extends Animal{
void meow(){ BabyCat c=new BabyCat();
System.out.println("meowing..."); c.weep();
}
} c.meow();

class BabyCat extends Cat{ c.eat(); }


void weep(){ }
System.out.println("weeping...");
}
}

Nourchene OUERHANI 177


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

Inheritance: Java Syntax


3. Hierarchical Inheritance
class Animal{
void eat(){
System.out.println("eating...");} class TestInheritance3{
}
public static void main(String args[]){
class Cat extends Animal{
void meow(){ Dog d=new Dog();
System.out.println("meowing..."); \\d.meow(); Compile-time error
}
} d.bark();

class Dog extends Animal{ d.eat(); }


void bark(){ }
System.out.println("barking...");
}
}

Nourchene OUERHANI 178


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

Inheritance: Java Syntax


Why multiple inheritance is not supported in java?

→ To reduce the complexity and simplify the language

Example:

A, B, and C are three classes: C class inherits A and B classes.

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.

Nourchene OUERHANI 179


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

Inheritance: Java Syntax


Why multiple inheritance is not supported in java?
class A{
void msg(){
System.out.println("Hello");}
}
class B{
void msg(){
System.out.println("Welcome");}
}
class C extends A,B{//suppose if it were

public static void main(String args[]){


C obj=new C();
obj.msg();//Now which msg() method would be invoked?}
}
Nourchene OUERHANI 180
Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

Inheritance: Object Class


● Object class is the default superclass and is present in java.lang
package.
● Every class in Java is directly or indirectly derived from the Object
class:
➔ If a class does not extend any other class then it is a direct child
class of Object and if extends another class then it is indirectly
derived.
● Object class methods are available to all Java classes.

● Object class is the root of the class hierarchy.

Nourchene OUERHANI 181


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

Inheritance: Object Class


getClass() wait()
clone()

Lorem ipsum
tempus
notify() notifyAll()

Object Class
Methods
Lorem ipsum
toString() hashCode()
tempus

equals() finalize()

Nourchene OUERHANI 182


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

Inheritance: Super Keyword

The super keyword in Java is a reference variable which is used to refer


immediate parent class object.

1. super can be used to refer immediate parent class instance


variable.
2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.

Nourchene OUERHANI 183


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

Inheritance: Super Keyword


1. Super can be used to refer immediate parent class instance variable

class Animal{
protected String color="white"; } class TestSuper1{

public static void


class Dog extends Animal{
main(String args[]){
private String color="black";
Dog d=new Dog();
void printColor(){
System.out.println(color);//prints color d.printColor();
of Dog class }}
System.out.println(super.color);//prints
color of Animal class
} }
Nourchene OUERHANI 184
Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

Inheritance: Super Keyword


2. Super can be used to invoke parent class method
class Animal{

public void eat(){System.out.println("eating...");}}


class TestSuper2{
class Dog extends Animal{
public static void
public void eat(){
main(String args[]){
System.out.println("eating bread...");}
Dog d=new Dog();
public void bark(){
d.work();
System.out.println("barking...");}
}}
public void work(){

super.eat();

bark(); }}

Nourchene OUERHANI 185


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

Inheritance: Super Keyword


3. super is used to invoke parent class constructor
class Animal{

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");
}}

Nourchene OUERHANI 186


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

Inheritance: Super Keyword


class Person{
protected int id;
protected String name; class TestSuper5{
public Person(int id,String name){ public static void
this.id=id;
this.name=name; }} main(String[] args){

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);}}

Nourchene OUERHANI 187


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

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.

Nourchene OUERHANI 188


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

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

● When an instance of Superclass is assigned to a Subclass variable,


then it’s called downcasting.
Cat c = new Cat();
Animal a = c;
Cat c1 = (Cat) a;
Nourchene OUERHANI 189
Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

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.

Nourchene OUERHANI 190


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

Polymorphism
class Animal {
public void animalSound() {
System.out.println("The animal makes a sound");
}}

class Cat extends Animal {


public void animalSound() {
System.out.println("The cat says: meow meow");
}}

class Dog extends Animal {


public void animalSound() {
System.out.println("The dog says: bow wow");
}}

Nourchene OUERHANI 191


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

Polymorphism
We can achieve polymorphism in OOP using the following ways:

1. Method Overloading:This is an example of compile time or static


polymorphism

2. Method Overriding: This is an example of runtime time or dynamic

polymorphism

3. Operator Overloading

Nourchene OUERHANI 192


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

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.

➔ This is called method overriding.

It is an example of runtime time (or dynamic) polymorphism.

In this case, the same method will perform one operation in the
superclass and another operation in the subclass.

Nourchene OUERHANI 193


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

Polymorphism: Overriding

Nourchene OUERHANI 194


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

Polymorphism: Overloading

● In a Java class, we can create methods with the same name


if they differ in parameters.

● This is known as method overloading in Java.

● The same method will perform different operations based on


the parameter.

Nourchene OUERHANI 195


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

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.

Nourchene OUERHANI 196


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

Polymorphism: Operator Overloading


Some operators in Java behave differently with different operands.

● + operator is overloaded to perform numeric addition as well as


string concatenation
● operators like &, |, and ! are overloaded for logical and bitwise
operations.
In languages like C++, we can define operators to work differently for
different operands. However, Java doesn't support user-defined
operator overloading.

Nourchene OUERHANI 197


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

Inheritance and composition

● In object-oriented programming, inheritance and


composition are two ways that allow the reuse of
classes
● Inheritance translates the term “Is a”
● The composition translates the term “has a”

Nourchene OUERHANI 198


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

Java inner Class


● In Java, it is also possible to nest classes (a class within a
class). The purpose of nested classes is to group classes
that belong together, which makes your code more
readable and maintainable.
● To access the inner class, create an object of the outer
class, and then create an object of the inner class.

Nourchene OUERHANI 199


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

Java inner Class


class OuterClass {
private int x = 10;

class InnerClass {
private int y = 5;
}
}

public class Main {


public static void main(String[] args) {
OuterClass myOuter = new OuterClass();
OuterClass.InnerClass myInner = myOuter.new InnerClass();
System.out.println(myInner.y + myOuter.x);
}
}

// Outputs 15 (5 + 10)

Nourchene OUERHANI 200


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

Java inner Class


Private Inner Class
An inner class can be private.
→ Outside objects can not access the inner class when it is declared as a
private class.

Static Inner Class


An inner class can be static.
→ It can be accessed without creating an object of the outer class.

Nourchene OUERHANI 201


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

Java inner Class


class OuterClass {
int x = 10;

private class InnerClass {


int y = 5;
}
}

public class Main {


public static void main(String[] args) {
OuterClass myOuter = new OuterClass();
OuterClass.InnerClass myInner = myOuter.new InnerClass();
System.out.println(myInner.y + myOuter.x);
}
}
//an error occurs Main.java:13: error: OuterClass.InnerClass has private access in
OuterClass OuterClass.InnerClass myInner = myOuter.new InnerClass();

Nourchene OUERHANI 202


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

Java inner Class


class OuterClass {
int x = 10;

static class InnerClass {


int y = 5;
}
}

public class Main {


public static void main(String[] args) {
OuterClass.InnerClass myInner = new OuterClass.InnerClass();
System.out.println(myInner.y);
}
}

// Outputs 5
Nourchene OUERHANI 203
Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

Abstraction: Abstract Class


● Data abstraction is the process of hiding certain details and showing
only essential information to the user.
● Abstraction can be achieved with:
○ Abstract classes
○ Interfaces
● The abstract keyword is a non-access modifier, used for classes and
methods:
○ Abstract class: is a restricted class that cannot be used to create
objects (to access it, it must be inherited from another class).
○ Abstract method: can only be used in an abstract class, and it
does not have a body. The body is provided by the subclass.

Nourchene OUERHANI 204


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

Abstraction: Abstract Class


Abstract Method
1) Abstract method has no body.
2) Always end the declaration with a semicolon
public abstract void sound();
3) It must be overridden: An abstract class must be extended and in a
same way abstract method must be overridden.
4) A class has to be declared abstract to have abstract methods.

Nourchene OUERHANI 205


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

Abstraction: Abstract Class


// Abstract class
abstract class Animal {
// Abstract method (does not have a body)
public abstract void animalSound();
// Regular method
public void sleep() {
System.out.println("Zzz");}
}

// Subclass (inherit from Animal)


class Cat extends Animal {
public void animalSound() {
// The body of animalSound() is provided here
System.out.println("The cat says: meow meow");}
}

class Main {
public static void main(String[] args) {
Cat cat = new Cat(); // Create a Cat object
cat.animalSound();
cat.sleep();}
}

Nourchene OUERHANI 206


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

Abstraction: Abstract Class: WHY?


We have a class Animal that has a method sound() and the subclasses: Dog,
Lion, Horse, Cat etc.
→ The animal sound differs from one animal to another.
→ There is no point to implement this method in the superclass.
→ Every child class must override this method to give its own implementation
details, like Cat class will say “Meow” in this method and Dog class will say
“Woof”.
→By making this method abstract we made it compulsory to the subclasses
to implement this method( otherwise you will get compilation error).
This way we ensures that every animal has a sound.

Nourchene OUERHANI 207


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

Abstraction: Abstract Class


● Abstract class can have abstract methods(methods without body) as well as
concrete methods (regular methods with body).

● An abstract class can not be instantiated, which means it is not allowed to


create an object of it.

● 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.

Nourchene OUERHANI 208


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

Abstraction: Abstract Class


● A non-abstract class is referred as Concrete class: it cannot have
abstract methods. (Animal is an abstract class and Cat is a concrete
class).
● An abstract class has no use until it is extended by some other
classes.
● If an abstract method is declared in a class then the class must be
declared abstract.
● If a class is not having any abstract method, it can be marked as
abstract.

Nourchene OUERHANI 209


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

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)
}

Nourchene OUERHANI 210


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

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
};
}

Nourchene OUERHANI 211


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

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();}}

Nourchene OUERHANI 212


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

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.

Nourchene OUERHANI 213


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

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.

Nourchene OUERHANI 214


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

Abstraction: Interface
interface FirstInterface {
void firstMethod(); // interface method
}

interface SecondInterface {
void secondMethod(); // interface method
}

class DemoClass implements FirstInterface, SecondInterface {


public void firstMethod() {
System.out.println("First interface..");}

public void secondMethod() {


System.out.println("Second interface...");}
}

class Main {
public static void main(String[] args) {
DemoClass myObj = new DemoClass();
myObj.firstMethod();
myObj.secondMethod();}
}

Nourchene OUERHANI 215


Object Oriented Programming (OOP) OOP Fundamentals: JAVA OOPL

Abstraction: Abstract Class VS Interface

Nourchene OUERHANI 216


Object Oriented Programming (OOP)

That’s All Folks


Just for this lesson😉
Nourchene OUERHANI

You might also like