oop-1
oop-1
OOP- CoSc1012 1
Classroom Rules
• Late comer will only tolerated for the first 5 minutes of every class
• Talk to me and Not to each other
• Do not sleep
• Do not use phones
• Fail to obey the Classroom rule → face 2 → 3 class ban
OOP- CoSc2051 2
Introduction to Object-
Oriented Programming
OOP- CoSc2051 3
Introductions
• Chapter 1: Introduction to O O P
– Types of programming paradigms
– Overview of O O principles
– Editing, Compiling and Interpreting
OOP- CoSc2051 4
Introductions
▪ All computer programs consist of two elements: code and data.
▪ A Programming language is a notational system for describing
tasks/computations in a machine and human readable form.
▪ Most computer languages are designed to facilitate certain operations
and not others:
OOP- CoSc2051 5
Introductions
• What is a "programming paradigm"?
– Paradigm: "A philosophical and theoretical framework of a scientific
school or discipline within which theories, laws, and generalizations and
the experiments performed in support of them are formulated;
OOP- CoSc2051 7
Programming Paradigms : PL
.
Imperative/ Object
Algorithmic Declarative Oriented
(HOW) (all about what)
Functional Logic
Programming Programming
Algol Lisp Prolog Smalltalk
Cobol Haskell Simula
PL/1 ML C++ , C#
Ada Miranda Java ,VB
Fortran APL
C
Modula-3
OOP- CoSc2051 8
Imperative paradigms
▪ First do this and next do that.
▪ It is based on commands that update variables in storage.
▪ The main : Explicitly tells the computer "how" to accomplish it.
▪ The Latin word imperare means “to command”.
▪ E.g G O T O command
▪ It works by changing the program state through assignment statements.
▪ It performs step by step task by changing state.
▪ The paradigm consist of several statements and after execution of all
the result is stored.
OOP- CoSc2051 10
Imperative paradigms
▪ Examples of Imperative programming paradigm:
▪ C : developed by Dennis Ritchie and Ken Thompson
▪ Fortran : developed by John Backus for IBM
▪ Basic : developed by John G Kemeny and Thomas E Kurtz
public class Main {
public static void main(String[] args) {
OOP- CoSc2051 12
Declarative Programming
import java.util.Arrays;
System.out.println(sum); // Output: 15
}
}
▪ import java.util.Arrays; is necessary to use the Arrays class.
▪ An array of integers is defined: int[] numbers = {1, 2, 3, 4, 5};.
▪ The Arrays.stream(numbers) method converts the array into a
stream, which allows you to perform operations on it.
OOP- CoSc2051 13
Functional programming paradigms
▪ In this paradigm we express computations as the evaluation of
mathematical functions.
OOP- CoSc2051 14
Functional programming paradigms
▪ Advantages:
▪ The high level of abstraction, removes the possibility of committing many
classes of errors;
▪ The lack of dependence on assignment operations, allowing programs to be
evaluated in many different orders.
▪ This evaluation order independence makes function-oriented languages
good candidates for programming massively parallel computers;
▪ The absence of assignment operations makes the function-oriented programs
much more amenable to mathematical proof and analysis than are imperative
programs.
▪ Disadvantages:
▪ Perhaps less efficiency
▪ Problems involving many variables or a lot of sequential activity that are
sometimes easier to handle imperatively or with object-oriented programming.
OOP- CoSc2051 15
Logic programming paradigms
▪ The LP takes a declarative approach to problem-solving.
▪ Various logical assertions about a situation are made, establishing all
known facts.
OOP- CoSc2051 16
Logic programming paradigms
▪ While the functional paradigm emphasizes the idea of a
mathematical function, the logic paradigm focuses on predicate
logic, in which the basic concept is a relation.
▪ Logic languages are useful for expressing problems where it is not
obvious what the functions should be.
OOP- CoSc2051 17
Logic programming paradigms
clauses
brother(X,Y) :- /* X is the brother of Y */
/* if there are two people F and M for which*/
father(F,X), /* F is the father of X */
father(F,Y), /* and F is the father of Y */
mother(M,X), /* and M is the mother of X */
mother(M,Y), /* and M is the mother of Y */
male(X). /* and X is male */
▪ Predicates
▪ mother(sara, jack). /* sara is the mother of jack */
▪ is fact.
▪ Query
? mother(sara, jack).
Yes
OOP- CoSc2051 18
Logic programming paradigms
▪ Advantages:
▪ system solves the problem, so the programming steps themselves
are kept to a minimum;
OOP- CoSc2051 19
The Object-Oriented Paradigm
▪ Object Oriented Programming (OOP) is a paradigm in which real-
world objects are each viewed as separate entities having their own
state which is modified only by built in procedures, called methods.
OOP- CoSc2051 20
Fundamental Principles of O O P
1. Objects
2. Classes
3. Methods and Messages
4. Abstraction
5. Inheritance
6. Encapsulation
7. Polymorphism
OOP- CoSc2051 21
O O P Concepts
▪ In object-oriented programming (OOP), programs are organized into
objects.
▪ The properties of objects are determined by their class
▪ Objects act on each other by passing messages.
▪ Object
▪ Definition:
An object is a software bundle that has State and Behavior.
▪ Software Objects are often used to model real-world objects.
▪ Example:
dogs have states (name, color, hungry, breed) and
behaviors (bark, fetch, and wag tail).
OOP- CoSc2051 22
Object Examples
▪ Example 1: Dogs
▪ States: name, color, breed, and “is hungry?”
▪ Behaviors: bark, run, and wag tail
▪ Example 2: Cars
▪ States: color, model, speed, direction
▪ Behaviors: accelerate, turn, change gears
OOP- CoSc2051 23
Class
▪ Definition: A class is a blueprint that defines the states and the
behaviors common to all objects of a certain kind.
▪ In the real world, you often have many objects of the same kind.
▪ For example, a guard dog, herding dog, snoop dog . . .
▪ Even though all dogs have four legs, and bark, each dog’s behavior is
independent of other dogs.
class Dog {
▪ For example:
// state and behavior
▪ Dog #1 is a black Poodle,
}
▪ Dog #2 is a red Irish Setter
OOP- CoSc2051 24
Methods
▪ An Object's behavior is defined by its methods
▪ Methods, like fields, are written inside the braces of the class
▪ Methods can access the fields (the state) of their object and can change
them
class Dog {
String name; // field
// behavior
public void bark()
{
...
}
}
OOP- CoSc2051 25
Message
▪ Definition: Software objects interact and communicate with each other
by sending messages to each other.
▪ Example: when you want your dog to gather a herd of goats, you
whistle and send him out.
OOP- CoSc2051 26
Inheritance
▪ Inheritance is a mechanism in which one object acquires all the states
and behaviors of a parent object.
▪ Inheritance allows child classes inherits the characteristics of existing
parent class
base class /
derived class inherits parent class
OOP- CoSc2051 29
Inheritance – Example
Base class
Person
+Name: String
+Address: String
Employee Student
+Company: String +School: String
+Salary: double
OOP- CoSc2051 30
Encapsulation
▪ Encapsulation is a process of wrapping code and data together into a
single unit.
OOP- CoSc2051 31
Encapsulation – Example
▪ Example: Complete television is single box where all the mechanism
are hidden inside the box all are capsuled.
Person
-name : String
-age : TimeSpan
OOP- CoSc2051 32
Encapsulation – Benefits
▪ Ensures that structural changes remain local:
▪ Changing the class internals does not affect any code outside of the class
▪ Changing methods' implementation does not reflect the clients using
them
OOP- CoSc2051 33
Polymorphism
▪ Polymorphism is a concept in which we can execute a single
operation in different ways.
OOP- CoSc2051 34
Polymorphism
▪ Why handle an object of given type as object of its base type?
– To invoke abstract operations
– To mix different related types in the same collection
▪ E.g. List<object> can hold anything
– To pass more specific object to a method that expects a parameter
of a more generic type
– To declare a more generic field which will be initialized and
"specialized" later
OOP- CoSc2051 35
Polymorphism
Figure Abstract
action
+CalcSurface() : double
Concrete
class Square Circle
-x : int -x : int
-y : int -y : int
Overriden -size : int -radius: int Overriden
action action
OOP- CoSc2051 36
Abstraction
▪ Abstraction is a process of hiding the implementation details and
showing only functionality to the user.
▪ Abstraction means hiding internal details and showing the required things.
– E.g.: pressing the accelerator will increase the speed of a car.
– But the driver doesn’t know how pressing the accelerator increases
the speed – they don't have to know that.
OOP- CoSc2051 37
Overview of Java Programming
▪ Java is a high-level, general-purpose, object-oriented, and secure
programming language.
OOP- CoSc2051 38
Overview of Java Programming
▪ Key Features of Java
▪ Object-Oriented: Everything in Java is an object, promoting modularity and
extensibility.
▪ Platform-Independent: Java code compiles to platform-independent
bytecode, executed by the JavaVirtual Machine (JVM).
▪ Simple and Easy to Learn: Designed for readability and ease of use.
▪ Secure: Built-in security features prevent unauthorized access and malicious
code execution.
▪ Robust: Compile-time error checking and runtime checks minimize errors.
▪ Multithreaded: Supports concurrent execution of multiple threads.
▪ Interpreted: Bytecode is translated on-the-fly by the JVM.
▪ High Performance: JIT (Just-In-Time) compilers optimize execution speed.
▪ Distributed: Designed for internet-based distributed systems.
▪ Dynamic: Adapts to evolving environments.
OOP- CoSc2051 39
Overview of Java Programming
▪ Basic structure of a Java program.
▪ Documentation Section: The doc section is optional but
important.
▪ Package Declaration:
▪ Also optional, the package declaration comes after the doc section.
▪ It specifies the package in which the class resides.
▪ Only one package statement is allowed per Java program.
▪ The package name helps organize classes and avoids naming conflicts.
▪ Import Statements:
▪ Java packages contain predefined classes and interfaces.
▪ To use a class from a specific package, we need to import it.
▪ The import statement precedes the class declaration.
▪ You can either import a specific class or all classes from a package.
OOP- CoSc2051 40
Overview of Java Programming
▪ Basic structure of a Java program.
▪ Class Definition: The heart of a Java program is the class.
▪ A class contains fields (variables) and methods (behaviors).
▪ The public class keyword defines a class.
▪ Class Variables and Local Variables:
▪ Class variables (also called instance variables) belong to the class and are
shared among all instances.
▪ Local variables are declared within methods and have limited scope.
▪ Methods/Routines/Behaviors:
▪ Methods define the behavior of a class.
▪ The main method is the entry point for execution.
▪ Other methods perform specific tasks.
OOP- CoSc2051 41
Overview of Java Programming
▪ Basic structure of a Java program.
// Documentation section (optional)
// Package declaration (optional)
package IntroJavaProgram;
//Import statements (if needed)
import java.util.Scanner;
//Class definition
public class HelloJava {
// Class variable (optional)
static String greeting = "Hello, World!";
OOP- CoSc2051 44
Overview of Java Programming
▪ The Compiler and the Java Virtual Machine
▪ Java Virtual Machine (JVM):
▪ The JVM is an abstract machine that enables your computer to run Java
programs.
▪ The JVM manages memory, garbage collection, and other runtime aspects.
OOP- CoSc2051 45
Overview of Java Programming
▪ The process of compiling and running your first Java program.
▪ Prerequisites:
1. Java Development Kit (JDK) installed on your computer.
2. A text editor or an integrated development environment (IDE) to
write and edit your Java code.You can choose from options like
Notepad++, Eclipse, IntelliJ IDEA, or NetBeans.
1. Write the Code: Type the following code into the file:
public class HelloJava {
public static void main(String[] args) {
System.out.println(“Hello World”);
}
}
OOP- CoSc2051 47
Overview of Java Programming
▪ The process of compiling and running your first Java program.
▪ To run your first program, type the following at the command prompt:
c:\java>java MyFirstJava.java
▪ Although the file name includes the .class extension , this part of
the name must be left off when running the program with the Java
interpreter.
OOP- CoSc2051 48
Overview of Java Programming
▪ The process of compiling and running your first Java program.
• Compile the Program: Compiling Java
Syntax:
System.out.print(message);
System.out.println(message);
Example
System.out.print("Hello world...\n");
System.out.println("Hello world...");
System.out.print( "The answer is: ");
System.out.print( 3.14 );
Input and Output…
Escape Sequence
The backslash (\) is called an escape character.
It indicates that a “special character” is to be output.
Sequence Description
\n Newline. Position the screen cursor to the beginning of the next line.
\t Horizontal tab. Move the screen cursor to the next tab stop.
Scanner Class
Scanner class is introduced to simplify the task of getting input
from the user
To use Scanner class, you must declare a Scanner variable and
create an instance of the Scanner class.
Example
static Scanner sc = new Scanner(System.in);
To read an input value from the user, you can use one of the
methods of the Scanner class.
There is a method to accept every primitive data type.
Method Explanation
boolean nextBoolean() Reads a boolean value from the user
byte nextByte() Reads a byte value from the user
double nextDouble() Reads a double value from the user
float nextFloat() Reads a float value from the user
int nextInt() Reads an int value from the user
String nextLine() Reads a String value from the user
long nextLong() Reads a long value from the user
short nextShort() Reads a short value from the user
Input and Output…
Example:
import java.util.Scanner;
public class ScannerApp {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
System.out.print("Enter an integer: ");
int x = sc.nextInt();
System.out.println("You entered " + x);
}
}
Datatypes and Variables
▪ In Java, types refer to the kinds of values that can be stored and
manipulated in a program.
▪ Java is a statically-typed language, which means that the type of a
variable must be declared before it is used.
▪ There are different types of values that can be stored and manipulated:
▪ Integers (int): These store whole numbers without decimals.
▪ Floating-Point Numbers (float):These store numbers with decimals.
▪ Characters (char): Used to store single characters, such as 'A', 'b', or '5'.
▪ Boolean Values (boolean):These represent true or false conditions.
▪ Strings (String): Strings store text, like "Hello" or "Java is awesome!".
– A sequence of characters. In Java, strings are objects.
OOP- CoSc2051 57
Datatypes and Variables
▪ There are different types of values that can be stored and manipulated:
▪ Reference Data Types:
▪ Objects: Instances of classes.
Person person1 = new Person();
▪ Arrays: Collections of elements of the same type.
int[] numbers = {1, 2, 3, 4, 5};
▪ Enumerations (Enums):
▪ A special data type that enables a variable to be a set of predefined
constants.
enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY,
FRIDAY, SATURDAY
}
Day today = Day.MONDAY;
OOP- CoSc2051 58
Datatypes and Variables
▪ Data Types: Default Values
▪ It's not always necessary to assign a value when a field is declared.
▪ Fields that are declared but not initialized will be set to a reasonable
default by the compiler.
Data Type Default Value (for fields)
byte 0
short 0
int 0
long 0L
float 0.0f
double 0.0d
char '\u0000'
String (or any null
object)
boolean false
OOP- CoSc2051 59
Datatypes and Variables
▪ In Java, a variable is a named location in the computer's memory that
stores a value of a particular type.
OOP- CoSc2051 60
Datatypes and Variables
▪ Here are the key points about variables in Java:
2. Naming Rules: Variable names in Java must adhere to certain rules:
– Must start with a letter, underscore (_), or dollar sign ($).
– Can be followed by letters, digits, underscores, or dollar signs.
– Case-sensitive.
int myVariable;
double _price;
String $name;
3. Assignment:
– Values are assigned to variables using the assignment operator (=).
– The value on the right side is assigned to the variable on the left
isindte.x = 10;
double y = 2.5;
String greeting = "Hello, World!";
OOP- CoSc2051 61
Datatypes and Variables
▪ Here are the key points about variables in Java:
2. Scope: Variables have different scopes:
– Local variables:
– Declared inside a method or block; limited to that block.
– Instance variables(Non-Static Fields):
– Belong to an instance of a class;Available throughout the class.
– Class Variables (static) : Shared among all instances of a class.
– E.g: static int numGears = 6
– Parameters Variables :
– E.g: public static void main(String[] args).
– Here, the args variable is the parameter to this method.
OOP- CoSc2051 62
Datatypes and Variables
▪ Here are the key points about variables in Java:
2. Scope:
– Variables have different scopes:
public class MyClass {
// Instance variable
int instanceVar;
// Local variable
int localVar = 5;
Casting
To create a conversion between two incompatible types, you
must use a cast.
A cast is simply an explicit type conversion.
Casting is similar to conversion, but isn’t done automatically.
Variables and Data Types…
String to Number
To convert a string to a primitive type, you use a parse
method of the appropriate wrapper class.
Constant
A constant is a variable whose value you can’t change once
it has been initialized.
It is also called final variable
To declare a constant, you add the final keyword to the
variable declaration, like this:
final double PI = 5;
OOP- CoSc2051 69
Arrays
▪ An array is a collection of similar types of data, allowing you to store
multiple values under a single variable name.
▪ You can make an array of any type int, double, String, etc..
▪ All elements of an array must have the same type.
▪ An array is an indexed list of values.
▪ The index starts at zero and ends at length-1.
▪ An array is defined using TYPE[].
▪ Arrays are just another type.
▪ int[] values; // array of int
▪ int[][] values; // int[] is a type
OOP- CoSc2051 70
Arrays
▪ To create an array of a given size, use the operator new :
int[] values = new int[5];
▪ or you may use a variable to specify the size:
int size = 12;
int[] values = new int[size];
▪ Array Initialization:
▪ Curly braces can be used to initialize an array.
▪ It can ONLY be used when you declare the variable.
int[] values = { 12, 24, -23, 47 };
☻ Quiz: Is there an error in this code?
int[] values = {1, 2.5, 3, 3.5, 4};
OOP- CoSc2051 71
Arrays
▪ Accessing Arrays
▪ To access the elements of an array, use the [] operator: values[index].
▪ Example:
int[] values = { 12, 24, -23, 47 };
values[3] = 18; // {12,24,-23,18}
int x = values[1] + 3; // {12,27,-23,18}
▪ The length variable
▪ Each array has a length variable built-in that contains the length of
the array.
OOP- CoSc2051 73
Arrays: 2-Dimensional Arrays
• In Java, a 2-dimensional array is essentially an array of arrays.
• In Java, 2D arrays are stored as arrays of arrays.
• It can be thought of as a matrix where each element is identified by two
indices - one for the row and another for the column.
• Creating a 2D Array:
– To create a two-dimensional array, you define a data type followed by
two sets of square brackets.
– Each array within the 2D array is enclosed in its own set of curly
braces.
OOP- CoSc2051 76
Control Structures
• In Java, control structures are constructs that allow you to alter the flow
of your program based on certain conditions or repetitions.
if (CONDITION) {
// Statements to be executed if the condition is true
}
int x = 10;
if(x > 5) {
System.out.println("x is greater than 5");
}
• In this example, if the condition x > 5 is true, the statement inside the
curly braces will be executed, and "x is greater than 5" will be printed to
the console.
OOP- CoSc2051 79
Control Structures
• Conditional Branches: ➔ if else
• The else statement is used to execute a block of code if the same
condition from the if statement is false.
• In this case, if y > 5 is false, the statements inside the else block will be
executed.
• Remember that the condition in the if statement should be a boolean
expression, which means it evaluates to either true or false.
OOP- CoSc2051 79
Control Structures
• Conditional Branches: ➔ if else if
• In Java, the combination of if and else if statements is used when you
have multiple conditions to check, and you want to execute different
blocks of code based on the evaluation of these conditions.
• The if-else if structure allows you to create a series of conditions, and
the first one that evaluates to true will have its corresponding block of
code executed.
if (condition1) {
// Statements to be executed if condition1 is true
} else if (condition2) {
// Statements to be executed if condition2 is true
}
// ... add more else if blocks if needed
else {
// Statements to be executed if none of the
conditions is true
}
OOP- CoSc2051 81
Control Structures
• Conditional Branches: ➔ switch
• The switch statement evaluates the expression once.
• It compares the value of the expression with the values of each case.
• If a match is found, the associated block of code executes.
• The break keyword is used to exit the switch block after executing a case.
• The default case is optional and runs when no other case matches.
switch (expression) {
case value1:
// Code to execute if expression matches value1
break;
// More cases...
default:
// Code to execute if no case matches
}
OOP- CoSc2051 82
Control Structures
• Conditional Branches: ➔ switch
int day = 4; // Assuming 1 represents Monday, 2 represents
Tuesday, and so on
switch (day) {
case 1:
System.out.println("Monday");
break;
case 4:
System.out.println("Thursday");
break;
default:
System.out.println("Invalid day");
}
• The default case handles situations where none of the specified cases match.
OOP- CoSc2051 83
Quiz
• Write a java program that prints letter grades based on
– 90 – 100 = A+
– 85 – 90 = A-
– 80 – 85 = A
– 75 – 80 = B+
– Else F by accepting value from a user.
OOP- CoSc2051 84
Control Structures
• Conditional Branches: ➔ Loops
• Loops allow you to repeat a set of instructions as long as a specified
condition remains true.
• for Loop:
– The for loop provides a concise way to write a loop structure.
– It combines initialization, condition testing, and increment/decrement
in one line.The for loop is an entry control loop.
for (initialization; testing-condition; increment/decrement)
{
// Statements...
}
for (int j = 0; j <= 10; j++) {
System.out.print(j); // 012345678910
}
OOP- CoSc2051 85
Control Structures
• Conditional Branches: ➔ Loops
• while Loop:
– The while loop executes a block of code while a given Boolean
condition is true.
while (boolean condition) {
// Loop statements...
}
– The while loop is an entry control loop (checks condition before
execution).
int i = 0;
while (i <= 10) {
System.out.println(i);
i++;
}
OOP- CoSc2051 86
Control Structures
• Conditional Branches: ➔ Loops
• do-while Loop:
– The do-while loop executes a block of code at least once, even if the
condition is false.
OOP- CoSc2051 87
Quiz
• FizzBuzz Problem Statement
• FizzBuzz is a well-known coding problem that frequently appears in
entry-level job interviews.
• FizzBuzz problems test your logical thinking and how well you know
loops and control flow.
• Write a program that prints the numbers from 1 to 100.
• But for multiples of three print "Fizz" instead of the
number and for the Multiples of five print "Buzz".
• For numbers which are multiples of both three and five
print "FizzBuzz".
OOP- CoSc2051 88
Assignment
1. Write a program that produces the following shape. The output produced
by this program is shown here:
*********
********
*******
******
*****
****
***
**
*
2. Write a program that adds the odd integers between 1 and
99, using a for structure. Display the sum on a console.
Assignment
3. Write a program accepts a number from user and then displays all
even numbers between 1 and the number accepted.
4. Write a program that accepts three numbers a, b, and c and then
display the largest of the three.
End of Chapter 1
OOP- CoSc2051 91