oopchapter3
oopchapter3
INTRODUCTION
INHERITANCE
POLYMORPHISM
ENCAPSULATION
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.
ancestors.
The already existing class is called the parent class, or super-class, and the new class is called the
The subclass inherits (reuses) the non-private members (methods and variables) of the super-class,
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)
Student and Teacher have the UserId, Inheritance allows you to write new classes that
LastName field and the getFName() and The existing class whose properties are inherited is
Classes often have a lot of state and The new class that inherits from the super class is
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,
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
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
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
E. Hybrid Inheritance: In simple terms you can say that Hybrid inheritance is a combination of the above
Note: Java does not support any combination with multiple inheritance.
13
INHERITANCE … (10)
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 }
}
*******************************
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
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
When binding is performed before the program is run, it’s called early binding. also called [static
When the binding occurs at run-time based on the type of object, it’s called late binding. also
When late binding is implemented, there must be some mechanism to determine the type of the
That is, the compiler still doesn’t know the object type, but the method-call mechanism finds out
Methods with same name, but the compiler uses two mechanisms to differentiate
Number of parameters
Data-type of parameters
24
POLYMORPHISM … (4)
public int sum (int x, int y){ OverloadDemo dem = new OverloadDemo();
} dem.sum(4,5, 6);
} }
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.
}} 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
Encapsulation can be a powerful tool for protecting data from unauthorized users through
information hiding.
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
ACCESS MODIFIERS
Access modifiers in Java are keywords that determine the scope and visibility of classes, methods,
They are fundamental to object-oriented programming as they help enforce encapsulation, a core
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)
Different NO NO NO YES
package Non-
Subclass
32
ENCAPSULATION … (5)
Class. encapsulation.
ERROR: We cannot
access private instance
variable from other class
SAME PACKAGE NON-SUBCLASS
35
ENCAPSULATION … (7)
FUNCTION ENCAPSULATION
CLASS ENCAPSULATION
Like function encapsulation, a class must be declared private to remove user access.
o Prevention of unauthorized access: Encapsulation allows you to restrict access to sensitive data
o Controlled modification: You can define rules for how data is accessed and modified through
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
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
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)
abstraction is a design level process that focuses on hiding the complex details and
} }
}
class Derived extends Base { D.Method1();
} }
40
HOMEWORK
System.out.println("Find area "); Shapes myShape = new Shapes(); // Create a Shapes object
}
public void area(int r) { myShape.area();
} myShape.area(6.0,1.2);
System.out.println("Triangle area="+0.5*b*h);
} }
System.out.println("Rectangle area="+l*b);
}}
41
HOMEWORK
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
private int age; // private field public static void main(String[] args) {
} }
} }
43
HOMEWORK
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