Chapter 2 - OOP for CS
Chapter 2 - OOP for CS
By: Sinodos G
Introduction
• Object • Encapsulation
• Class • Abstraction
• Polymorphism • Method
• Inheritance • Message
2
Object
A programming entity that contains state (data) and behavior (methods).
• State: A set of values (internal data) stored in an object.
• Behavior: A set of actions an object can perform, often reporting or
modifying its internal state.
Objects can be used as part of larger programs to solve problems.
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
3
Cont’d
An Object has two primary components:
state – properties of the object
behavior – operations the object can perform
4
Class
A class is the blueprint from which individual objects are created.
5
Classes and Objects
6
Creating objects of a class
• Object’s created:
• ObjectName.VariableName
• ObjectName.MethodName(parameter-list)
7
Methods
a collection of statements that are grouped together to perform an
operation.
Creating Method
Syntax
public static int methodName(int a, int b) {
// body
}
Explanations:
public static − modifier
int − return type
methodName − name of the method
a, b − formal parameters
int a, int b − list of parameters
8
Method Calling
a method, it should be called for using
There are two ways in which a method is called:-
method returns a value or
returning nothing (no return value).
9
The methods returning void is considered as call to a statement.
Example:
System.out.println("This is tutorialspoint.com!");
10
Passing Parameters by Value
• While working under calling process, arguments is to be passed.
• These should be in the same order as their respective parameters in
the method specification.
• Parameters can be passed by value or by reference.
• Passing Parameters by Value means calling a method with a
parameter.
• Through this, the argument value is passed to the parameter.
11
Instance fields
also known as instance variables.
They are attributes or properties that belong to a specific instance
(object) of a class.
Each object created from a class can have its own set of values for
these instance fields.
Declaration:
• declared within a class but outside Example:
of any methods or constructors. public class Person {
• define the state of an object // Instance fields
• marked with access modifiers like private String name;
private, public, or protected to private int age;
control their visibility and access. }
12
Cont’d
Initialization:
• Instance fields can have default values if not explicitly
initialized.
Example,
• numeric types are initialized to 0, and reference types
(like objects) are initialized to null.
13
Cont’d
Access:
• Instance fields are accessed using the dot (.) notation
• Each object has its own set of field values.
Person person1 = new Person();
person1.name = "Alice";
Example: person1.age = 25;
Person person2 = new Person();
person2.name = "Bob";
person2.age = 40;
Scope:
• Instance fields exist as long as the object they are associated
with is in memory.
• They are used to store and manage the object's data, and they
are not shared across different instances of the class.
14
Enumerated types
referred to as enums,
special data type used to define a set of constant values
are a data type in computer programming that define a set
of named constant values.
powerful for creating well-structured code.
used to represent a fixed set of related constants
used to represent a finite, discrete set of options or
choices.
useful to improve code readability and maintainability
15
Cont’d …
To create an enum, use the enum keyword
Constants must be in uppercase letters
Example:
Example
enum Color {
enum Level { RED,
LOW,
GREEN,
MEDIUM,
BLUE
HIGH
}
}
Color selectedColor =
can access enum constants with the dot Color.GREEN;
Example:
Level myVar = Level.MEDIUM;
16
Cont’d . . .
Example:
write a java program tat check if today is Sunday using java
enumerated.
enum Day {
SUNDAY, MONDAY, TUESDAY,
WEDNESDAY, THURSDAY,
if (today == Day. SUNDAY) {
FRIDAY, SATURDAY
System.out.println(“day is SUNDAY");
}
else
public class EnumDay{
System.out.println(“ not Sunday ");
public static void main(String[] args) {
}
Day today = Day. SUNDAY;
}
}
17
Cont’d
• Enums are often used in switch statements to check for
corresponding values:
switch(myVar) {
enum Level { case LOW:
LOW, System.out.println("Low level");
MEDIUM, break;
HIGH case MEDIUM:
} System.out.println("Medium level");
break;
public class Main {
case HIGH:
public static void main(String[] args) {
System.out.println("High level");
Level myVar = Level.MEDIUM; break;
}
}
}
18
Enum and loops
The enum type has a values() method, which returns an array of all
enum constants.
This method is useful when you want to loop through the constants
of an enum:
enum Level {
LOW, MEDIUM, HIGH
}
Example: }
public class Main {
public static void main(String[] args) {
for (Level myVar : Level.values()) {
System.out.println(myVar);
}
}
19
Constructors
a special method that is used to initialize objects.
called when an object of a class is created.
It can be used to set initial values for object attributes
fundamental building blocks of classes
Constructor is invoked at the time of object creation.
Purpose:
• are special methods used to create and initialize objects of a class.
• called when an object is instantiated (created) using the new
keyword.
Naming:
• have the same name as the class, and they do not have a return type,
not even void.
20
Cont’d
Example:
public Person() {
// Initialization code goes here
}
}
21
Cont’d
Types of constructors
Default Constructor
Parameterized Constructor
Copy Constructor:
• Creates a new object by copying the values from an existing
object.
Static Constructor
Private Constructor:
• Used to prevent the instantiation of a class, often in singleton
design patterns.
22
Cont’d
Types of Constructors
• Default constructor (No-argument constructor)
• A constructor that have no parameter
• Default values to the object like 0, null etc. depending on the type.
<class_name>()
{
}
• Parameterized constructor
• A constructor that have parameters
• Used to provide different values to the distinct objects.
<class_name>(parameter list)
{
}
23
Example
class Student {
int id;
String name;
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[]) {
Student s1=new Student();
Student s2=new Student();
s1.display();
s2.display();
}
} class_name object_name=new class_name();
24
Example:
class Student{
int id;
String name;
public static void main(String args[]){
Student(int i,String n){ Student s1 = new Student(111,“Abay");
id = i;
name = n; Student s2 = new Student(222,“Gebissa");
}
s1.display();
void display(){ s2.display();
}
System.out.println(id+" "+name);
}
}
25
Cont’d
Example:
public class Main {
int x;
public Main() {
x = 5; // Set the initial value for the class attribute x
}
public static void main(String[] args) {
Main aa = new Main();
// Create an object of class Main (This will call the constructor)
System.out.println(aa.x);
// Print the value of x
}}
26
Cont’d
27
Java - Methods
a collection of statements that are grouped together to perform an
operation. Example:
• When you call the System.out.println() method, the system actually
executes several statements in order to display a message on the
console.
Creating Method
Considering the following example to explain the syntax of a method
Syntax
public static int methodName(int a, int b) {
// body
}
28
Cont’d
Constructor Overloading
• a technique in which a class can have any number of
constructors that differ in parameter lists.
• The compiler differentiates these constructors by taking into
account the number of parameters in the list and their type.
Method Overloading
• class have multiple methods by the same name but different
parameters, it is known as Method Overloading.
29
Example: Constructor Overloading
class Student{
int id; void display(){
String name; System.out.println(id+" "+name+" "+age);
int age; }
Student(int i,String n){ public static void main(String args[]){
id = i; Student s1 = new
name = n;
Student(111,“yemane");
}
Student(int i,String n,int a){ Student s2 = new
id = i; Student(222,"Aryan",25);
name = n; s1.display();
age=a; s2.display();
} }
}
30
Methods
a block of code which only runs when it is called.
You can pass data, known as parameters, into a method.
used to perform certain actions, and they are also known as functions.
Objects interact with each other by passing messages.
Purpose
• functions defined within a class to perform specific tasks or
operations.
• They define the behavior of the class and enable you to encapsulate
functionality.
Naming
• Methods have names that are relevant to the action they perform.
• They can have various return types, including void for methods that do
not return a value.
31
Cont’d
32
Cont’d
34
Cont’d
Example:
static int add(int x, int y) {
return x + y;
}
static double add(double x, double y) {
return x + y;
}
public static void main(String[] args) {
int num1 = add(8, 5);
double num2 = add(4.3, 6.26);
System.out.println("int: " + num1);
System.out.println("double: " + num2);
}
35
Example of Method
36
Example – Constructor
// Method to add the two integers System.out.println("The sum of the two integers is: " +
public int add() { sum);
return num1 + num2; }
} }
37
Access Modifiers
are keywords that determine the visibility or accessibility of classes,
methods, fields, and other members within a program.
There are four main access modifiers in Java:
• public: Accessible from anywhere.
• protected: Accessible within the same package and in subclasses.
• default: Accessible only within the same package.
• private: Accessible only within the same class.
38
Cont’d
Example:
public class Numbers {
final int x = 10;
final double pi = 3.14;
public static void main(String[] args) {
Find Output?
Numbers aa = new Numbers();
aa.x = 50;
aa.PI = 25;
System.out.println(aa.x);
System.out.println(pi.x);
}
}
39
Cont’d
public class Main {
static void myStaticMethod() {
System.out.println("Static methods . . .");
} • A static method means that
it can be accessed without
// Public method
creating an object of the
public void myPublicMethod() { class, unlike public:
System.out.println("Public methods . . .");
} public static void main(String[ ] args) {
myStaticMethod(); // Call the static method
// myPublicMethod(); error
41
Encapsulation
A fundamental principles of object-oriented programming in Java.
Means 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
Bundling of data (attributes or fields) and methods (functions) that
operate on that data into a single unit, known as a class.
The class is typically declared as private, and access to that data is
controlled through public methods, which are called getters and
setters.
This ensures that the data is only accessed and modified in a
controlled and consistent manner, promoting data integrity and
security.
42
Cont’d
Encapsulation is one of the four fundamental OOP concepts.
The other three are inheritance, polymorphism, and
abstraction.
a mechanism of wrapping the data (variables) and code acting
on the data (methods) together as a single unit.
Variables of a class will be hidden from other classes, and can
be accessed only through the methods of their current class.
Therefore, it is also known as data hiding.
To achieve encapsulation in Java −
• Declare the variables of a class as private.
• Provide public setter and getter methods to modify and
view the variables values.
43
Example
44
Cont’d
The public setXXX() and getXXX() methods are the access points of the
instance variables of the EncapTest class.
Normally, these methods are referred as getters and setters. Therefore,
any class that wants to access the variables should access them
through these getters and setters.
The variables of the EncapTest class can be accessed using the
following program:
public class RunEncap {
public static void main(String args[]) {
EncapTest encap = new EncapTest();
encap.setName("James");
encap.setAge(20);
encap.setIdNum("12343ms");
System.out.print("Name : " + encap.getName() + " Age : " + encap.getAge()); } }
45
Cont’d
• Information Abstraction:
• abstracts the implementation details of a class and focuses on
what the class can do rather than how it does it.
46
Benefits of encapsulation
Data Protection
• prevent accidental or unauthorized modifications
• 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.
Flexibility
• allows you to change the internal implementation of a class
without affecting the code that uses the class
Code Maintainability
• It promotes code organization and makes it easier to understand
and maintain by providing a clear and well-defined structure.
Reusability
• used as building blocks in different parts of a program or in
different programs altogether, enhancing code reusability.
47
Example
public class Student { // Public setter method for name
// Private fields (data) public void setName(String name) {
private String name; this.name = name;
private int age; }
End of Chapter 2
Next Chapter 3
49