Chapter 4Updated
Chapter 4Updated
1
Outline
Encapsulation and data abstraction
2
Data abstraction and encapsulation
Imagine you have a treasure chest with valuable items. You want to keep the items safe and secure, so
you put them inside the treasure chest and lock it. You don't want anyone to directly access the items
without your permission or knowledge.
The valuable items represent the data (attributes) inside the class.
The act of putting the items inside the chest and locking it represents encapsulation
3
Data abstraction and encapsulation
Encapsulation, in a general sense, is the act of enclosing or containing something within a capsule or
container
Classes normally hide the details of their implementation from their client . This is called information
hiding. Access control is often referred to as implementation hiding.
The client cares about what functionality program offers, not about how that functionality is
implemented. This is referred to as data abstraction. wrapping data and methods with implementation
hiding is often called encapsulation.
Encapsulation can be described as a protective barrier that prevents the code and data being randomly
accessed by the other code defined outside the class.
4
Data abstraction and encapsulation
In the context of object-oriented programming, encapsulation refers to the bundling of data (attributes)
and methods (behaviors) together within a class and controlling access to them.
The term "encapsulation" in programming is just as enclosing or encapsulating related elements within
a protective container, similar to how we encapsulate objects in real-life containers to protect them.
In programming, encapsulation allows us to group related data and behaviors together, providing a way
to organize and structure code.
By encapsulating data and methods within a class, we establish boundaries and control access to the
internal workings of the class.
5
Data abstraction and encapsulation
It helps to safeguard the integrity of the data and provides a well-defined interface for interacting with the class.
The primary point of encapsulating data fields and methods together in a class is to promote proper information hiding
and to provide a well defined interface for interacting with the class.
Information Hiding:
It enables us to prevent direct access to the internal state of the object from outside the class.
protect the data integrity, ensuring that it can only be modified through controlled methods, thus preventing
unintended or incorrect usage.
Hiding the internal implementation details also reduces complexity and enhances code maintainability.
6
Data abstraction and encapsulation
Modularity and Organization
Encapsulation promotes modular design by grouping related data fields and methods together within a class.
It provides a logical and organized structure for your code, making it easier to understand, read, and
maintain.
With encapsulation, each class represents a distinct entity or concept, encapsulating its specific data and
behaviors, which improves code organization and separation of concerns.
Access Control:
Encapsulation allows you to control the visibility and access levels of data fields and methods.
By using access modifiers (e.g., public, private, protected), you can restrict access to certain members of the
class.
7
Data abstraction and encapsulation
.Access Control:
Example
This enables you to define a clear interface for
interacting with the class, hiding unnecessary
implementation details and exposing only the
essential methods and attributes.
8
Data abstraction and encapsulation
Example
Example
A class’s private variable can only be accessed by
its methods.
9
Continued…. Constructor and Encapsulation
The following are characteristics of well In Java, objects are constructed. Every time
designed encapsulated class
you make a new object, at least one
Data variables ,fields are hidden from the user constructor is invoked.
object Every class has a constructor, although if
Methods provide explicit service to the user we don't create one explicitly, the compiler
object but hide the implementation. will build one for you.
As long as the service do not change the The first thing to notice is that constructors
implementation can be modified without look an awful lot like methods. A key
impacting the user. difference is that a constructor can't have a
return type.
10
Continued….
The other BIG RULE, to understand about constructors is that they must have the same name as the class in which
they are declared.
Constructors can't be marked static (they are after all associated with object instantiation), they can't be marked
final or abstract (because they can't be overridden)
11
ENCAPSULATION IN ACHIEVING DATA ABSTRACTION
Encapsulation plays a vital role in achieving data abstraction. Let's explore how encapsulation is used as a data
abstraction process:
Encapsulation allows you to bundle related data fields (attributes) and methods (behaviors) together within a class.
Data fields represent the state or properties of an object, while methods define the operations or behaviors that can
be performed on the data.
By encapsulating data and methods within a class, you establish a cohesive unit that represents an abstraction of a
real-world entity or concept.
12
Hiding Implementation Details:
Encapsulation enables you to hide the internal implementation details of a class from external entities.
The internal state of an object, represented by its data fields, is kept private or protected, preventing direct access from
outside the class.
his information hiding ensures that the internal implementation details of a class are not exposed, promoting a higher
level of abstraction.
Providing an Interface:
Encapsulation provides a well-defined interface through which external entities can interact with the class.
The class exposes a set of public methods, while keeping the internal implementation details hidden
13
Providing an Interface:
Example
The class exposes a set of public methods, while keeping
the internal implementation details hidden.
14
Hiding Implementation Details:
Separating Interface from Implementation:
Encapsulation separates the interface (public methods) from the implementation (internal details) of a class.
This separation allows for better maintenance and evolution of the codebase.
Changes made to the internal implementation details do not impact the external users of the class, as long as the
interface remains unchanged.
This separation of concerns enables abstraction by providing a clear distinction between how the class is used and how
it internally accomplishes its tasks.
15
Hiding Implementation Details:
The public methods act as an abstraction layer, allowing users to manipulate the class's data and invoke its behaviors
Abstracting Complexity:
By encapsulating complex data structures and algorithms within a class, encapsulation serves as a form of data
abstraction.
Users of the class only need to understand and interact with the simplified interface provided by the public methods.
The complex details of how the data is stored, processed, or manipulated are abstracted away, making it easier for users
to work with the class.
16
SETTERS AND GETTERS
public methods, commonly known as getters and setters, serve as access points to the fields (variables) of a class from
the external Java world.
Getters:
Getters are public methods that allow external entities to access the values of private fields (variables) of a class.
Getters typically have the prefix "get“ followed by the name of the field they provide access to.
Getters provide read-only access to the values of the fields, allowing users to retrieve the current state of an object.
By encapsulating the fields and providing getters, you can control how the values are accessed and potentially add
additional logic or transformations if needed.
17
SETTERS AND GETTERS
Setters:
Setters are public methods that allow external entities to modify or set the values of private fields of a class.
Setters typically have the prefix "set“ followed by the name of the field they modify.
Setters provide write access to the fields, allowing users to update the state of an object.
By encapsulating the fields and providing setters, you can control how the values are modified, validate inputs, or
perform other operations when the field is updated.
18
Examples
Getter and setter
19
Examples
Getter and setter Example
20
Continued….
Example:
21
Polymorphism
► Polymorphism means "many forms", and it occurs when we have many classes that are related to each
other by inheritance.
Polymorphism enables you to write programs that process objects that share the same superclass as if
they’re all objects of that superclass, simplifying programming.
Polymorphism uses those methods to perform different tasks. This allows us to perform a single
action in different ways.
22
Inheritance in java
Inheritance is a fundamental concept in object oriented programming that allows classes
to inherit properties (fields and methods) from other classes.
Inheritance promotes code reuse and enables the creation of more specialized classes
based on existing classes.
The superclass serves as a template or blueprint for creating subclasses, which can add
new features or modify existing ones.
23
In object-oriented programming (OOP) Inheritance
Inheritance is a way to form new classes using classes that have
already been defined.
Inheritance is employed to help reuse existing code with little or no
modification.
The new classes, known as derived classes, inherit attributes and
behavior of the pre-existing classes, which are referred to as base
classes (or ancestor classes).
The inheritance relationship of sub- and superclasses gives rise to a
hierarchy.
polymorphism and inheritance are useful for code reusability: reuse
attributes and methods of an existing class when you create a new
class.
24
Inheritance in java
Subclasses inherit the fields and methods of the superclass and can also introduce their
own unique fields and methods.
The superclass is higher in the inheritance hierarchy and represents a more general or
abstract concept, while subclasses are lower in the hierarchy and represent more specific
or specialized concepts.
Subclasses inherit the attributes and behaviors of their superclass and can further
refine/embellish or specialize them as needed.
Inheritance supports the principle of "is-a“ relationship, where a subclass is considered to
be a specific type of the superclass. For example, a "Car" class can be a subclass of a
more general "Vehicle" class, as a car is a specific type of vehicle. Car is-a vehicle
25
Inheritance in java
This type of inheritance is not allowed in
In Java, inheritance is achieved using the
java.
extends keyword. A class can extend only Java allows only single inheritance to solve
one superclass, but multiple levels of this it brings interface.
inheritance can be created through a chain
of subclasses.
26
Private method can’t be overridden
In Java, an instance method can be overridden by a subclass if it is accessible,
meaning it can be accessed and invoked by other classes or subclasses.
However, a private method cannot be overridden because it is not accessible outside
its own class.
When a method is declared as private in a super class, it is intended to be used only
within that class only.
Private methods are not visible or accessible to other classes, including subclasses.
Therefore, it is not possible for a subclass to override a private method from its
superclass since it cannot access or modify the private method
27
Private method can’t be overridden
This restriction ensures encapsulation and prevents subclasses from altering the
behavior of private methods, maintaining the integrity and consistency of the
superclass.
Private methods are not accessible which means they can not be overridden in the
sum class
28
APPLICATIONS OF INHERITANCE
Specialization: Inheritance allows the creation of specialized classes or objects that
inherit data or behavior from a more general or parent class.
The new class or object can add additional data fields or behaviors that are specific to
its specialized nature.
This enables the modeling of more specific concepts in the program and promotes a
more organized and hierarchical structure in the codebase.
29
APPLICATIONS OF INHERITANCE
Overriding: One of the key features of inheritance is the ability to override methods
in the subclass.
This allows a subclass to provide its own implementation of a method that it inherits
from its superclass. By overriding a method, the subclass can modify or extend the
behavior defined in the superclass to suit its specific needs.
This enables customization and flexibility in the behavior of objects based on their
specific class types.
30
APPLICATIONS OF INHERITANCE
Code re-use: Inheritance promotes code reusability by allowing classes to inherit
properties and behaviors from existing classes.
► When a class inherits from another class, it automatically gains access to all the fields
and methods defined in the superclass. This eliminates the need to duplicate code and
promotes a more modular and efficient development approach.
► By reusing existing code through inheritance, developers can save time and effort by
leveraging the functionality and structure already implemented in the superclass.
31
APPLICATIONS OF INHERITANCE
Code re-use: Inheritance promotes code reusability by allowing classes to inherit
properties and behaviors from existing classes.
► When a class inherits from another class, it automatically gains access to all the fields
and methods defined in the superclass. This eliminates the need to duplicate code and
promotes a more modular and efficient development approach.
► By reusing existing code through inheritance, developers can save time and effort by
leveraging the functionality and structure already implemented in the superclass.
32
Inheritance
33
Inheritance
In Java inheritance is represented by the key word extends.
Syntax
modifier class SubclassName extends SuperclassName
{
//body
}
Example
public class Mammal extends Animal
{
//body
}
34
Inheritance
Note: Object is the super class of all Java Classes.
public class Student
{
protected String name;
public Student()
{
name = “”;
}
public Student(String s)
{
name = s;
}
public String getName()
{
return name;
35 }
Examples of Inheritance
36
Examples of Inheritance
37
“Instance of” operator
This can be used to identify whether an object Example
is an instance of a certain class or implements a
specific interface.
38
Super keyword
► The super keyword in java program is mainly used to infer the immediate parent class the
defined sub class.
► It paves the way to access and call members (Methods, variables and constructors) of the
super class inside the child class.
► When a class extends from an other class it inherits all the class members of the parent
class except the private members.
► It uses the super keyword to access its inherited members from the super class.
39
Super keyword
Member
1. Method
► If the subclass wants to define the method having the same name with the super class and
it wants to call the implementation of the super class it uses the super keyword .
► 2. Variables :
► As we have seen before when a class extends an other class it will inherit all non private
variables of the super class, but it can embellish itself with adding additional variables to
the existing super class variables.
► It uses the super keyword to infer the super class variables instead of reinventing them in
the
40
sub class/
Super keyword
Calling superclass’s constructor
► The subclass constructor automatically invoke the parent class constructor using super()
before initializing its specific variables.
► The initializing code defined in the super class is executed before the subclasses
initialization is executed.
► Generally, the super keyword enables the subclass to leverage and extend the functionality
of the super class within the subclass, which enable code reuse and create hierarchical
relationship between different classes
41
Super keyword
Calling superclass’s constructor example
42
Final Class and Final Method
► Final can be applied to class, variables and methods .
► It is typically used for classes that are intended to be secure, efficient, or provide
specialized functionality that should not be altered.
► It is commonly used to prevent subclasses from altering the behavior of a crucial method
that is essential to the class's functionality or consistency.
43
Example
44
Abstract Classes and Methods
Abstract classes
Sometimes it’s useful to declare classes for which you never intend to create objects.
Used only as superclasses in inheritance hierarchies, so they are sometimes called abstract
superclasses.
Subclasses must declare the “missing pieces” to become “concrete” classes, from which
you can instantiate objects; otherwise, these subclasses too, will be abstract.
An abstract class provides a superclass from which other classes can inherit and thus share a
common design.
Abstract Classes and Methods
Classes that can be used to instantiate objects are called concrete classes.
Such classes provide implementations of every method they declare (including those inherited).
Concrete classes provide the specifics that make it reasonable to instantiate objects.
Programmers often write client code that uses only abstract superclass types to reduce client code’s
dependencies on a range of subclass types.
When called, such a method can receive an object of any concrete class that directly or indirectly extends the
superclass specified as the parameter’s type.
Abstract methods are typically declared in abstract classes, which serve as blueprints for
other classes.
An abstract class can have one or more abstract methods along with regular (nonabstract)
methods.
Subclasses that extend an abstract class must implement all the abstract methods
inherited from the abstract class.
Subclasses that inherit an abstract method from an abstract class must provide an
implementation for that method.
Example
package ethioTechnoTube; class Dog extends Animal{
abstract class Animal{ Dog(String Name) {
protected String Name; super(Name);
Animal(String n) { }
this.Name=n; public void Status() {
} System.out.println("it is
protected abstract void barking");
Sound();//abtsract class }
public void Status() { @Override
System.out.println("it has protected void Sound() {
slept"); System.out.println(Name+":
}} Bark");
}}
.
Example
class Cat extends Animal{ Example
Cat(String Name) {//
constructor of the cat class
super(Name);
}
public void Status() {
System.out.println("the cat
has gone out");
}
@Override
protected void Sound() {
System.out.println(Name+" :
mew");}}
.
Case Study: Payroll System Using Polymorphism
Use an abstract method and polymorphism to perform payroll calculations based
on the type of inheritance hierarchy headed by an employee.
Hourly employees are paid by the hour and receive overtime pay (i.e., 1.5 times their hourly
salary rate) for all hours worked in excess of 40 hours
Base-salaried commission employees receive a base salary plus a percentage of their sales.
For the current pay period employees will receive an additional 10% to their base salaries.
Case Study: Payroll System Using Polymorphism (Cont.)
abstract class Employee represents the
general concept of an employee.
Subclasses: SalariedEmployee,
CommissionEmployee, HourlyEmployee
and BasePlusCommissionEmployee (an
indirect subclass)
Example
60
Interfaces Can Be Extended Example
One interface can inherit another by use
of the keyword extends.
61
Class Work
Make a group of 4 students 4th Group:
1st Group: Difference between java class Getter and setter methods
and main class with Example, conditional Inheritance with example
statements
2nd Group: Data inputs in java With
Example, how to instantiate an object,
3rd group: Method and Constructor with
example overriding and constructor
overloading
62