0% found this document useful (0 votes)
3 views

oopchapter3

oop concept
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

oopchapter3

oop concept
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

HARAMAYA UNIVERSITY

COLLEGE OF COMPUTING AND INFORMATICS


DEPARTMENT OF SOFTWARE ENGINEERING

OBJECT ORIENTED PROGRAMMING (SENG 2023)

CHAPTER THREE: PRINCIPLES OF OBJECT ORIENTED PROGRAMMING

COMPILED BY: GIZACHEW B.


2 CONTENTS

 INTRODUCTION

 INHERITANCE

 POLYMORPHISM

 ENCAPSULATION

 ABSTRACTION (Will be covered in Chapter 4)


3
INTRODUCTION

The Object Oriented Programming (OOP) is constructed over four major principles:

 Inheritance

 Polymorphism

 Encapsulation

 Abstraction
4
INHERITANCE … (1)

WHAT IS INHERITANCE?

 In the real world: We inherit behaviors from our mother and father.

 We also inherit behaviors from our grandmother, grandfather, and

ancestors.

 We might have similar eyes, the same smile, a different height . . .

but we are in many ways "derived" from our parents.

 Objects that are derived from other object "resemble” their

parents by inheriting both state (fields) and behavior(methods).


5
INHERITANCE … (2)

 Inheritance is a fundamental feature of object-oriented programming which enables the programmer

to write a class based on an already existing class.

 The already existing class is called the parent class, or super-class, and the new class is called the

subclass, or derived class.

 The subclass inherits (reuses) the non-private members (methods and variables) of the super-class,

and may define its own members as well.

 Inheritance is implemented in Java using the keyword extends.

 When class B is a subclass of class A, we say B extends A


6
INHERITANCE … (3)

public class Student { public class Teacher {


int UserId; int UserId;
String Username; String Username;
String Password; String Password;
String FirstName; String FirstName;
String LastName; String LastName;
String Batch; String AcademicRank;

public Student(String fname, String lname) { public Teacher(String fname, String lname) {
FirstName = fname; FirstName = fname;
LastName = lname; LastName = lname;
} }
public String getFName() { public String getFName() {
return FirstName; return FirstName;
} }
public String getBatch() { public String getARank() {
return Batch; return AcademicRank;
} }
public String Login() { public String Login() {
return “Welcome: ” + getFName(); return “Welcome: ” + getFName();
} }
} }
7
INHERITANCE … (4)

PROBLEM: Code Duplication SOLUTION: Inheritance

 Student and Teacher have the UserId,  Inheritance allows you to write new classes that

Username, password, FirstName, inherit from existing classes

LastName field and the getFName() and  The existing class whose properties are inherited is

Login() method in common called the "PARENT" or SUPER-CLASS

 Classes often have a lot of state and  The new class that inherits from the super class is

behavior in common called the "CHILD" or SUBCLASS

RESULT: Code duplicate! RESULT: Code reuse!


8
INHERITANCE … (5)
Student Teacher
int UserId; int UserId;
String Username; String Username;
String Password; String Password;
String FirstName; String FirstName;
String LastName; String LastName;
String Batch; String AcademicRank;
String getFName() String getFName()
String getBatch() String getARank()
String Login() String Login()
SOLUTION: Inheritance
Superclass User
Subclass Subclass
int UserId;
String Username;
String Password;
String FirstName;
Student String LastName; Teacher
String Batch; String getFName()
String Login() String AcademicRank;
String getBatch() String getARank()
9
INHERITANCE … (6)

public class User { public class Student extends User {


int UserId;
String Username; String Batch;
String Password; public Student(String fname, String batch)
String FirstName;
String LastName; {
public User (String FName) { super(fname); // calls User constructor
FirstName = FName;
} Batch = batch;
public String getFName() { }
return FirstName;
} public String getBatch() {
public String Login() { return Batch;
return “ | Welcome: ” + getFName();
} }
}
10
INHERITANCE … (7)

public class Teacher extends User { public class InheritanceDemo {


public static void main(String[] args) {
String AcademicRank;
Student st = new Student(“Ujulu", “II”);
public Teacher(String fname, String ARank) {
Teacher tr = new Teacher(“Gizachew", “Lect”);
super(fname); // calls User constructor
System.out.print("Student Name: " + st.getFName());
AcademicRank = ARank;
System.out.println( st.Login());
} System.out.print("Teacher Name: " + tr.getFName());
public String getARank() { System.out.println( tr.Login());

return AcademicRank; }

} }
OUTPUT
} Student Name: Ujulu | Welcome: Ujulu
} Teacher Name: Gizachew | Welcome: Gizachew
11
INHERITANCE … (8)

ADVANTAGES OF INHERITANCE.

 Code Reusability:- Inheritance automates the process of reusing the code of the super-classes in the

subclasses. With inheritance, an object can inherit its more general properties from its parent object,

and that saves the redundancy in programming.

 Code Maintenance:- Organizing code into hierarchical classes makes its maintenance and

management easier.

 Implementing OOP:- Inheritance enables the creation of a class hierarchy, allowing for a structured

representation of relationships between classes. This mirrors real-world relationships, making it

easier to model complex systems.


12
INHERITANCE … (9)

TYPES OF INHERITANCE

A. Single level inheritance:- Inheritance in which a class inherits from only one super class.

B. Multi-level inheritance:- Inheritance in which a class inherits from a class which itself inherits from

another class. Here a minimum of three classes is required.

C. Hierarchy inheritance:- Here two or more classes inherits from one class.

D. Multiple inheritance:- A class inherits from two or more classes. This type of inheritance is not

supported in Java. [achieved Using interfaces….. Will be covered in chapter 4].

E. Hybrid Inheritance: In simple terms you can say that Hybrid inheritance is a combination of the above

two inheritance types:{Hierarchical and Multiple; Hierarchical and Multi-level}

Note: Java does not support any combination with multiple inheritance.
13
INHERITANCE … (10)

1. SINGLE-LEVEL INHERITANCE 2. MULTI-LEVEL INHERITANCE

Class A {
Class A Class A
// Instance variables
Type method-name (parameter-list){
}
Class B Class B }
Class B extends A {
// Instance variables
Class A { Type method-name (parameter-list){
// Instance variables Class C }
Type method-name (parameter-list){ }
} Class C extends B {
} // Instance variables
Class B extends A { Type method-name (parameter-list){
// Instance variables }
Type method-name (parameter-list){ }
}
}
14
INHERITANCE … (11)

Class A {
Class A // Instance variables
Type method-name (parameter-list){
}
}
Class B extends A {
Class C // Instance variables
Class B Class D
Type method-name (parameter-list){
}
3. HIERARCHICAL INHERITANCE }
Class C extends A {
// Instance variables
Type method-name (parameter-list){
}
}
Class D extends A {
// Instance variables
Type method-name (parameter-list){
}
}
15
INHERITANCE … (12)

Class A {
4. MULTIPLE INHERITANCE // Instance variables
Type method-name (parameter-list){
}
}
Class A Class B
Class B {
// Instance variables
Type method-name (parameter-list){
Class C }
}
*******************************

ERROR! Class C extends A, B {


// Instance variables
Type method-name (parameter-list){ ************OR*****************
}} Class C extends A{
// Instance variables
Type method-name (parameter-list){
}}
JAVA DOES NOT SUPPORT Class C extends B{
MULTIPLE INHERITANCE // Instance variables
Type method-name (parameter-list){
}}
16
INHERITANCE … (13)

5. HYBRID INHERITANCE

Class A Class A

Class B Class C
Class B

Class D
Class C Class D

Hybrid of Hierarchical
and Multiple Inheritance Hybrid of Hierarchical
and Multi-level Inheritance
17
INHERITANCE … (13)
Class A {
// Instance variables
Type method-name (parameter-list){
}
Class A
} ERROR!
Class B extends A {
// Instance variables
Class B Class C Type method-name (parameter-list){
}
}
Class C extends A {
Class D // Instance variables
Type method-name (parameter-list){ JAVA DOES NOT
} SUPPORT HYBRID
Hybrid of Hierarchical } INHERITANCE
and Multiple Inheritance
Class D extends B, C {
// Instance variables
Type method-name (parameter-list){
}
}
18
INHERITANCE … (13)
Class A {
// Instance variables
Class A Type method-name (parameter-list){
}
}
Class B extends A {
Class B // Instance variables
Type method-name (parameter-list){
}
}
Class C Class D Class C extends B {
// Instance variables
Type method-name (parameter-list){
Hybrid of Hierarchical }
and Multi-level Inheritance }

Class D extends B{
// Instance variables
Type method-name (parameter-list){
}
}
19
INHERITANCE … (14)

INHERITANCE RULES

 Use the extends keyword to indicate that one class inherits from another

 The subclass inherits all the non-private fields and methods of the super-class

 The first thing a subclass constructor must do is call the super-class constructor to ensure that

the superclass is properly initialized before the subclass adds its own initialization.

 If the super class has a parameterized constructor, use the super keyword in the subclass

constructor to call the super-class constructor.

 Default superclass constructor will be implicitly invoked in subclass constructor without

using super keyword.


20
INHERITANCE … (15)

public class Vehicle { class Car extends Vehicle {


String Type; String Model;
public Vehicle() { Car() {
System.out.println("Vehicle constructor" ); System.out.println(“Car constructor”);
} }
} public static void main(String[] args) {
Car myCar = new Car();

If the super-class has default constructor, then that super-class }


}
constructor will-be called implicitly by subclass constructor OUTPUT

without using super keyword. Vehicle constructor


Car constructor
21
POLYMORPHISM … (1)

 Polymorphism is one of the principles in Object Oriented Programming paradigm.

 The term polymorphism means “a method the same as another in spelling but with different

behavior.”

 Polymorphism is the ability of objects to act depending on the run time type.

 Polymorphism allows programmers to send the same message to objects from different classes.

i.e., in its simplest from, polymorphism allows a single variable to refer to objects from different

classes.

 Polymorphism enables us to “program in the general” rather than “program in the specific”.
22
POLYMORPHISM … (2)

METHOD BINDING

 In general, connecting a method call to a method body is called binding.

 When binding is performed before the program is run, it’s called early binding. also called [static

binding] OR [compile-time binding]

 When the binding occurs at run-time based on the type of object, it’s called late binding. also

called [dynamic binding] OR [run-time binding.]

 When late binding is implemented, there must be some mechanism to determine the type of the

object at run-time and to call the appropriate method.

 That is, the compiler still doesn’t know the object type, but the method-call mechanism finds out

and calls the correct method body.


23
POLYMORPHISM … (3)

METHOD OVERLOADING | EARLY BINDING |STATIC BINDING

 Methods with same name, but the compiler uses two mechanisms to differentiate

the overloaded methods

 Number of parameters

 Data-type of parameters
24
POLYMORPHISM … (4)

public Class OverloadDemo { public static void main (String[] args){

public int sum (int x, int y){ OverloadDemo dem = new OverloadDemo();

System.out.print(“Sum of 2 integers=” + (x + y)); dem.sum(4,5);

} dem.sum(4,5, 6);

public int sum (int x, int y, int z){ dem.sum(4.5,5.3);

System.out.print(“Sum of 3 integers=” + (x + y + z)); }

} }

public int sum (double x, double y){


System.out.print(“Sum of 2 double=” + (x + y));
OUTPUT
}
Sum of 2 integers= 9
Sum of 3 integers =15
Sum of 2 double= 9
25
POLYMORPHISM … (5)

METHOD OVERRIDING | LATE BINDING |DYNAMIC BINDING

 Methods with same name and signature and applied on inheritance concepts.

 Methods of a subclass override the methods of a super class in a given inheritance hierarchy.

 Methods of a subclass implement the abstract methods of an abstract class.

 Methods of a concrete class implement the methods of an interface.


26
POLYMORPHISM … (6)

public class Animal { public class ExecutionClass{


void print() { public static void main(String[] args)
System.out.println(“SUPER CLASS”); {
}} Animal animal1 = new Animal();
class Dog extends Animal { Dog dog1 = new Dog();
} Cat cat1= new Cat();
class Cat extends Animal { animal1.print();
} dog1.print();
cat1.print();
OUTPUT
}
SUPER CLASS
}
SUPER CLASS

WITHOUT METHOD OVERRIDING SUPER CLASS


27
POLYMORPHISM … (6)

public class Animal { public Class ExecutionClass{


void print() { public static void main(String[] args)
System.out.print(“SUPER CLASS”); {
}} Animal animal1 = new Animal();
class Dog extends Animal { Dog dog1 = new Dog();
void print() { Cat cat1= new Cat();
System.out.print(“SUBCLASS DOG”); animal1.print(); Method print in Dog and in Cat
}} dog1.print(); override method print in Animal
class Cat extends Animal { cat1.print();
void print() { } OUTPUT

System.out.print(“SUBCLASS CAT”); } SUPER CLASS

}} SUBCLASS DOG
WITH METHOD OVERRIDING SUBCLASS CAT
28
ENCAPSULATION … (1)

 Every Java class that we create is an example of encapsulation because the class binds methods and

variables together. We write everything within the class that remains hidden from outside classes.

 When an object is created from a class, the methods and attributes are encapsulated inside the object.

 Data is not accessible to the outside world, and only those functions which are wrapped in the class can

access it.

 When we implement encapsulation, we declare the fields in the class as private to prevent other classes

from accessing them directly.


29
ENCAPSULATION … (2)

HIDING INFORMATION USING ENCAPSULATION

 Encapsulation can be a powerful tool for protecting data from unauthorized users through

information hiding.

 Object-oriented programming has four types of access modifiers: public, private,

protected, and default.

 Which modifier you use will depend on the level of protection your code requires.

 However, a good rule of thumb is to select the modifier with the most significant protection

that doesn’t hinder your code's functionality.


30
ENCAPSULATION … (3)

ACCESS MODIFIERS

 Access modifiers in Java are keywords that determine the scope and visibility of classes, methods,

variables, and constructors within an application.

 They are fundamental to object-oriented programming as they help enforce encapsulation, a core

principle restricting direct access to some of an object's components.

 PUBLIC: allows elements to be accessible from any other class in the application, regardless of the package

 PRIVATE: restricts access to the elements only within the class they are declared.

 PROTECTED: allows access within the same package or in subclasses. It might be in different package subclass.

 DEFAULT/NO MODIFIER: If a class does not have an access modifier assigned to it, it is given the default

access modifier. This means that any class within the same package can access the member.
31
ENCAPSULATION … (4)

DEFAULT PRIVATE PROTECTED PUBLIC

Same Class YES YES YES YES

Same package YES NO YES YES


Subclass

Same package YES NO YES YES


Non-Subclass

Different NO NO YES YES


package Subclass

Different NO NO NO YES
package Non-
Subclass
32
ENCAPSULATION … (5)

TYPES OF ENCAPSULATION IN OOP

 OOP has three ways to implement encapsulation:

 Member variable, MEMBER VARIABLE ENCAPSULATION

 Function, and  In member variable encapsulation also called data member

 Class. encapsulation.

 Classes are typically private by default, so data members are also

generally private members of a class.

 The public setter and getter method is required to access data

members within the encapsulation.


33
ENCAPSULATION … (6)

public class Customer {


private int custID;
public Customer(int id) {
custID=id;
}
public int getCustID() {
SAME CLASS
return custID;
}
public static void main(String[] args) {
Customer cust1=new Customer(2233);
System.out.println("Customer ID: " +cust1.custID);
}
}
34
ENCAPSULATION … (6)

public class Customer { public class customerDemo {


Correct (we can access by
private int custID; public static void main(String[] args) public getter method)

public Customer(int id) { {


custID=id; Customer cust1=new Customer(2233);
} Customer cust2=new Customer(4466);
public int getCustID() { System.out.println("Customer ID: " +cust1.getCustID());
return custID; System.out.println("Customer ID: " +cust1.custID);
}} }}

ERROR: We cannot
access private instance
variable from other class
SAME PACKAGE NON-SUBCLASS
35
ENCAPSULATION … (7)

FUNCTION ENCAPSULATION

 Function encapsulation refers to indicating a method or block of code as private to prevent

access by those not authorized to see it.

CLASS ENCAPSULATION

 Like function encapsulation, a class must be declared private to remove user access.

 Class encapsulation allows a particular class to be hidden or inaccessible to other classes.


36
ENCAPSULATION … (8)

BENEFITS OF USING ENCAPSULATION

 DATA PROTECTION AND SECURITY:

o Prevention of unauthorized access: Encapsulation allows you to restrict access to sensitive data

by using access modifiers (private, protected, public).

o Controlled modification: You can define rules for how data is accessed and modified through

getter and setter methods.

 IMPROVED CODE MAINTAINABILITY: Changes to the internal representation of data do not affect the external

code that uses the class. You can modify the implementation without impacting users of the class, as long as the public

interface (methods) remains the same.


37
ENCAPSULATION … (8)

BENEFITS OF USING ENCAPSULATION ….

 ENFORCEMENT OF BUSINESS RULES

o Encapsulation ensures that data adheres to specific business rules by centralizing validation logic within

the class.

o In encapsulation, instance variables (also known as attributes or fields) are typically initialized and

modified using constructors and methods, which allows you to incorporate validation logic.

o This ensures that any values assigned to the instance variables adhere to specific rules or constraints

defined by your business logic.

 MODULARITY

o Encapsulation helps in breaking down a complex system into smaller, manageable modules.

o Each class is responsible for its own data and behavior, leading to a modular design.
38
ENCAPSULATION … (9)

 The primary difference between ABSTRACTION and ENCAPSULATION is that

abstraction is a design level process that focuses on hiding the complex details and

implementation of the code.

 In contrast, encapsulation is an implementation level process that focuses on hiding

the data and controlling the visibility of the code.


39
HOMEWORK

STEP BY STEP OUTPUT | INHERITANCE


class Base { public void Method2() {

public Base() { System.out.println("Method2 called");

System.out.println("Base Constructor called"); }

} }

public void Method1() { public class InheritEx {

System.out.println("Method1called"); public static void main(String[] args) {

} Derived D = new Derived();

}
class Derived extends Base { D.Method1();

public Derived() { D.Method2();

System.out.println("Derived Constructor called"); }

} }
40
HOMEWORK

STEP BY STEP OUTPUT | STATIC POLYMORPHISM


class Shapes { class Main {

public void area() { public static void main(String[] args) {

System.out.println("Find area "); Shapes myShape = new Shapes(); // Create a Shapes object

}
public void area(int r) { myShape.area();

System.out.println("Circle area = "+3.14*r*r); myShape.area(5);

} myShape.area(6.0,1.2);

public void area(double b, double h) { myShape.area(6,2);

System.out.println("Triangle area="+0.5*b*h);
} }

public void area(int l, int b) { }

System.out.println("Rectangle area="+l*b);
}}
41
HOMEWORK

STEP BY STEP OUTPUT | DYNAMIC POLYMORPHISM

class Vehicle{ public static void main(String args[]){

//defining a method Car2 obj = new Car2(); //creating object

void run(){ obj.run(); //calling method

System.out.println("Vehicle is moving"); }

} }

}
//Creating a child class
class Car2 extends Vehicle{
//defining the same method as in the parent class
void run(){System.out.println("car is running
safely");
}
42
HOMEWORK

STEP BY STEP OUTPUT | ENCAPSULATION

class Person { class Main {

private int age; // private field public static void main(String[] args) {

public int getAge() { // getter method // create an object of Person

return age; Person p1 = new Person();

} // change age using setter

// setter method p1.setAge(24);

public void setAge(int age) { // access age using getter

this.age = age; System.out.println("My age is " + p1.getAge());

} }

} }
43
HOMEWORK

CODING | You are free to exercise OOP principles

1. Write a Java program to create a class Employee with a method called calculateSalary().

Create two subclasses Manager and Programmer. In each subclass, override the

calculateSalary() method to calculate and return the salary based on their specific roles.

2. Write a Java program to create a base class Shape with method calculateArea(). Create

three subclasses: Circle, Square, and Triangle. Override the calculateArea() method to

calculate and return the area of each shape.


TEACHING YOU IS GOOD LUCK

You might also like