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

OOP Principles (Encapsulation and Inheritance)

The document discusses object-oriented programming principles like encapsulation, inheritance, and polymorphism. It explains access modifiers, encapsulation, and how to create fully encapsulated classes in Java. It also covers inheritance concepts like subclasses, superclasses, overriding methods, and using the super keyword.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

OOP Principles (Encapsulation and Inheritance)

The document discusses object-oriented programming principles like encapsulation, inheritance, and polymorphism. It explains access modifiers, encapsulation, and how to create fully encapsulated classes in Java. It also covers inheritance concepts like subclasses, superclasses, overriding methods, and using the super keyword.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

OOP Principles

What Do you think


about this Concept
Encapsulation
✓ Before Discussing about Encapsulation first we have to understand
access modifiers.

✓ The Access Modifiers in java specifies the accessibility(visibility) or


scope of a field, method, constructor, or class

✓ Java provides 4 types of Access Modifiers

❖ Public

❖ Protected

❖ Private

❖ Default
Public: The access level of a public modifier is everywhere. It can be
accessed from within the class, outside the class, within the package and
outside the package.

Protected: The access level of a protected modifier is within the package


and outside the package through child class. If you do not make the child
class, it cannot be accessed from

outside the package.


Default: The access level of a default modifier is only within the package.
It cannot be accessed from outside the package. If you do not specify
any access level, it will be the default.

Private: The access level of a private modifier is only within the class. It
cannot be accessed from outside the class.
The principle of encapsulation is that all of an object’s data is contained
and hidden in the object and access to it restricted to methods of that
class.

✓ Code outside of the object cannot directly access object fields.

✓ All access to an objects field takes place through its methods.

✓ By hiding internal data structures and processes and publishing only


well-defined methods for accessing your objects.

We can create a fully encapsulated class in java by making all the data
members of the class Private. Then we can use public setter(mutator) and
getter(accessor) methods.
for access control. we need to build setter method for all instance
variable, and find a way to force other code to call the setters rather
than access the data directly.

✓ It is just like a Capsule which is mixed of several medicines.

Advantage of Encapsulation

✓ By providing only a setter or getter method, you can make the class
read-only or write-only. In other words, you can skip the getter or setter
methods.

✓ It provides you the control over the data. Suppose you want to set the
value of id which should be greater than 100 only, you can write the
logic inside the setter method. You can write the logic not to store the
negative numbers in the setter methods.
✓ It is a way to achieve data hiding in Java because other class will not
be able to access the data through the private data members.

✓ The encapsulate class is easy to test. So, it is better for unit testing.

this keyword

✓ Every object can access a reference to itself with keyword this


(sometimes called this reference).

✓ Gives access to the current class instance.

Usage of this keyword

❖ Scope Ambiguity Resolving

✓ If a local variable or parameter in a method has the same name as a

field (instance variable) of the class, the field is hidden until the block
terminates execution this is called Shadowing.

✓ If the field is an instance variable, precede its name with this keyword
and a dot(.) as in general form this.x, where x is the instance variable.
public class Motorcycle
{
public int driverIntensity;
public String name;
public void setDriverName(String name){
name= name;
}
The formal parameter name will shadow the instance variable name.
So, in this case we are assigning a variable back to itself.
Solution

Inform the compiler that you want to set the current objects name field to
the incoming name parameter, simply use this to resolve the ambiguity.
public class Motorcycle
{
public int driverIntensity;
public String name;
public void setDriverName(String name){
this.name= name;
}
❖ Constructor Channing
✓ This design is helpful when you have a class that defines multiple
constructors.

✓ Given that constructors often validate the incoming arguments to


enforce various business logics (rules). It can be quite common to find
redundant validation logic within a class’s constructor set.

✓ Constructor Chaining allows you to maintain your initializations from a


single location with multiple constructors.
✓ A cleaner approach is to design the constructor that takes the
greatest number of arguments as “the master constructor” and have its
implementation perform the required validation logic.
public class Student
{
String name;
int id;
public Student (String n) {
this(n,0);
}
public Student (String n, int idno) {
if(n.length()<15){
name=n;
}
id=idno;
}
Inheritance
✓ In OOP, we often organize classes in hierarchy to avoid duplication
and reduce redundancy.
✓ We can save time during program development by basing new class
on existing proven and debugged high-quality software.
✓ The classes in the lower hierarchy inherit all the members (instance
variables and methods) from the higher hierarchies.
✓ A class in the lower hierarchy is called a subclass (or derived, child,
extended class).
✓ A class in the upper hierarchy is called a superclass (or base, parent
class).
✓ We put all the common variables and methods into the super classes,
and leave the specialized variables and methods in the subclasses.
✓ Those common variables and methods do not need to be repeated in
all the subclasses.

✓ A subclass inherits all the variables and methods from its super classes,
including its immediate parent as well as all the ancestors.
✓ We can refer to these inherited methods and variables if they were
declared locally in the class.
✓ A subclass is not a "subset" of a superclass. In contrast, subclass is a
"superset" of a superclass.
✓ It is because a subclass inherits all the variables and methods of the
superclass; in addition, it extends the superclass by providing more
variables and methods.

❖ How to Derive Subclasses

✓ In Java, you define a subclass using the keyword "extends".


✓ Inheritance represents the “IS-A” relationship which is also known as a
parent-child r/ship.
✓ In java Multiple Inheritance is not supported through class. Each class is
derived from exactly one directly superclass. i.e., Single Inheritance

Example: In the above example we create a sub class


Goalkeeper by using this Statement.

class Goalkeeper extends SoccerPlayer {...}


✓ UML Notation: The UML notation for inheritance is a solid line with a hollow
arrowhead leading from the subclass to its superclass as shown:

✓ We derive a subclass called Cylinder from the superclass Circle.


✓ We reuse the class Circle. We not reinvent the wheels rather the class cylinder inherits
all the member variables (radius and color) and methods (getRadius(), getArea(),
among others) from its superclass Circle.
✓ It further defines a variable called height, two public methods - getHeight() and
getVolume() and its own constructors.
Protected Members
▪ Visibility modifiers affect the way the class member can be used
in a child class.
▪ public items are directly accessible from anywhere, while private
items can be accessed only by the class that has defined them
▪ Variables and methods declared with private visibility cannot be
referenced by name in a child class.
▪ When a base(parent) class defines protected data or protected
members, it establishes a set of items that can be accessed
directly by any descendant.
▪ It provides more encapsulation than public visibility, but is not as
tightly encapsulated as private visibility.
▪ The benefit of defining protected members in a base class is that
derived types no longer have to access the data indirectly using
public methods.
▪ When you define protected members, you are creating a level of
trust b/n the Parent class and child class.
▪ Protected modifier can’t be applied to the top-level classes and
interfaces.
Super keyword
✓ It refers to immediate parent class object.
✓ Whenever you create the instance of subclass, A sub class instance is
treated an instance of parent class which is referred by super reference
variable.
Usage of Super Keyword
• can be used to refer immediate parent class instance variable.
• can be used to invoke immediate parent class method.
• can be used to invoke immediate parent class constructor. i.e.,
Constructors are not inherited, even though they have public visibility.
If we override the method that is available in our parent class, we can use
super keyword in order to invoke the super class version of the method.
We will discuss the overriding concept in next session.
class Animal{
We can also use super keyword to
String color="white";
}
refer the data members or field of
class Dog extends Animal{
parent class in case if parent class String color="black";
void printColor(){
and child class have same fields. System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class

For example: In the below }


}
example super keyword is used in class TestSuper1{
public static void main(String args[]){
sub class constructors in order to
Dog d=new Dog();
invoke the parent class constructor. d.printColor();
}}
}
}
public class Word2{

public static void main (String[] args){

Dictionary2 webster = new Dictionary2(1500,52500);

System.out.println (“total pages”+webster.getPages());

System.out.println (“total definitions”+webster.getDefinitions());

System.out.println (“Definitions per page”+


definitions”+webster.computeRatio());

}
✓ A child constructor is responsible for calling the parent Constructor.
✓ If the child constructor invokes the parent (constructor) by using the
super reference, it must be the first line of code of the constructor.
✓ In a subclass, if we want to use both the superclass version and the
overriding subclass version of a method super key word is used to
invoke the parent version of the method.
✓ This means we don’t want to completely replace the superclass version
rather we want to extend the functionality.
Overriding Methods
✓ Overriding just means that a subclass redefines one of its inherited
methods when it needs to change or extend the behavior of that
method.
✓ Instance variable are not overridden because they don’t define any
special behavior, so a subclass can give an inherited instance
variable any value it chooses.
✓ The new method must have the same signature as the parent’s
method, but can have a different body.
✓ The type of the object executing the method determines which
version of the method is invoked.

public class Messages {

public static void main (String[] args) {

Thought parked = new Thought();

Advice dates = new Advice();

parked.message();

dates.message(); // overridden

}
✓ When you call a method on an object Reference, you are calling the
most specific version of the method for that object type. In the other
words, the “lowest one wins” in the inheritance tree.
❖ Final Method
✓ If a method is declared with the final modifier, it cannot be
overridden.
✓ This guarantees that the final method implementation will be used by
all direct and indirect subclasses in the hierarchy.
✓ Methods that are declared private are implicitly final, because it is
not possible to override them in a sub class. This Is the same with
Static methods.
❖ Final Class
✓ Cannot extended to create a subclass. E.g., String Class
❖ Types of Inheritance
1) Single Inheritance: A subclass inherit the features of one super class

2) Multilevel Inheritance: A subclass will be inheriting a base class and


as well as it serves as the base class to other class.

3) Hierarchical Inheritance: one class serves as a superclass for more


than one subclass.
▪ The Object Class
✓ A class called Object is defined in the java.lang package of the java
standard class library.
✓ All classes are derived from the Object class.
✓ If a class is not explicitly defined to be the child of an existing class, it
is assumed to be the child of the Object class
✓ Therefore, the Object class is the ultimate root of all class hierarchies.
✓ The Object class contains a few useful methods, which are inherited by
all classes.
For E.g., the toString method is defined in the Object class.

✓ Every time we define the toString method, we are actually overriding


an inherited definition.
✓ The toString method in the Object class is defined to return a string
that contains the name of the object’s class along with some other
information
✓ The equals method of the Object class returns true if two references
are aliases
✓ We can override equals in any class to define equality in some more
appropriate way (Content equality).

Has A Relation Ship


✓ A class can have references to objects of other classes as members.
✓ It is called composition or has-a relationship.
✓ Code reusability can be achieved.
E.g., Alarm Clock objects needs to know the current time and the time when it’s
supposed to sound its alarm.
✓ It is a unidirectional association i.e., one-way relationship.
Public Employee {
Int id;
String name;
Address address;// Address is a class
public class Address {
public Employee (int id, String name, Address address) { String city, state, country;
this.id = id; public Address (String city, String state, String country) {
this.name = name; this.city = city;
this.address=address; this.state = state;
this.country = country;
public String toString(){ }
return String.format(“%s %s\n %s %s \n %s %s\n %s %s\n, “name”, name,
“City”, address.city, “State”, address.state, “Country”, address.country ) }
}

public static void main (String[] args) {


Address address1=new Address("A.A","Mexico","Ethiopia");
Address address2=new Address("Adama","","Ethiopia");
Employee e=new Employee (111,"", address1);
Employee e2=new Employee (112,"” ,address2);
System.out.println(e);
System.out.println(e2);}}
}
1. }

You might also like