Object oriented programming Chapter 04
Object oriented programming Chapter 04
OOP Concepts
Slide 1
© Information Technology
Encapsulation
• Encapsulation is a practice to bind related functionality (Methods) & Data
(Variables) in a protective wrapper (Class) with required access modifiers
(public, private, default & protected) so that the code can be saved from
unauthorized access by outer world and can be made easy to maintain.
• Encapsulation is the technique of making the fields in a class private and
providing access to the fields via public methods.
• If a field is declared private, it cannot be accessed by anyone outside the class,
thereby hiding the fields within the class.
• For this reason, encapsulation is also referred to as data hiding. However, it is
possible to access them if we provide public get and set methods.
The set method sets the variable value.
The get method returns the variable value. Slide 2
© Information Technology
Example
public class EncapTest{
public class RunEncap{
t p u t: 20
private String name; O u e :
public static void main(String args[]){ e s Ag
private int age;
EncapTest encap = new EncapTest(); e : Jam
public int getAge(){ Nam
encap.setName("James");
return age;
}
encap.setAge(20);
public String getName(){ System.out.println("Name : " + encap.getName()+ " Age : "+
encap.getAge());
return name;
}
}
}
public void setAge( int newAge){ • The public methods are the access points to this class' fields from the
age = newAge; outside java world.
} • Normally, these methods are referred as getters and setters.
public void setName(String newName){ • Therefore any class that wants to access the variables should access
name = newName; them through these getters and setters.
} Slide 3
© Information Technology
Inheritance
The inheritance is the process of acquiring the properties of one class to another
class.
In java, using the inheritance concept, we can use the existing features of one
class in another class.
The inheritance provides code re-usability. With the help of code re-usability, the
commonly used code in an application need not be written again and again.
The class which provides features to another class is called parent class.
The class which receives features from another class is called child class.
In java, we use the keyword extends and Implement to create a child
class or to apply inheritance.
With use of the extends keyword the subclasses will be able to inherit all the
properties of the super class except for the private properties of the superclass.
Slide 4
© Information Technology
Inheritance
There are five types of
inheritances:
Simple Inheritance (or)
Single Inheritance
Multiple Inheritance
Multi-Level Inheritance
Hierarchical Inheritance
Hybrid Inheritance
Slide 5
© Information Technology
//single inheritance
//multilevel Inheritance
class ParentClass{ class ParentClass{
int a; int a;
void setData(int a) { void setData(int a) {
this.a = a; this.a = a;
} }
}
} class ChildClass extends ParentClass{
class ChildClass extends ParentClass{ void showData() {
void showData() { System.out.println("Value of a is " + a);
System.out.println("Value of a is " + }
a); }
} class ChildChildClass extends ChildClass{
void display() {
} System.out.println("Inside ChildChildClass!");
public class SingleInheritance { }
public static void main(String[] args) }
{ ChildClass obj = new public class MultiLevelInheritance {
ChildClass(); public static void main(String[] args)
{ ChildChildClass obj = new
obj.setData(100);
ChildChildClass();
obj.showData(); obj.setData(100);
} obj.showData(); Output:
} Output: obj.display(); Value of a is 100
Value of a is 100 } } Inside ChildChildClass!
Slide 6
© Information Technology
//Hierarchical Inheritance
class ParentClass{
int a;
void setData(int a) { public class HierarchicalInheritance {
this.a = a;
public static void main(String[] args) {
}
} ChildClass child_obj = new
class ChildClass extends ParentClass{
ChildClass();
void showData() {
System.out.println("Inside child_obj.setData(100);
ChildClass!");
child_obj.showData();
System.out.println("Value of a is " +
a); ChildClasstwo childToo_obj = new
}
ChildClasstwo();
}
class ChildClasstwo extends ParentClass{ childToo_obj.setData(200);
void display() {
childToo_obj.display();
System.out.println("Inside
ChildClassToo!"); }
System.out.println("Value of a is " + u t p u t: s !
} O
l d C l as
a);
e C hi 1 0 0 o!
In s i d i s
}
e o fa l as s To
} Valu ChildC 0
e 0
I n s id o f a is 2
e
© Information Technology
Valu Slide 7
Method overloading
• Method Overloading is the situation that two or more methods in the same
class have the same name but different arguments.
• As you can see in the example below, we have the same method add() taking
two parameters but with different data types.
• Due to overloading we can now call the add method by either passing it a
String or int.
public class OverLoadingExample{
public void add(int i, int j){
• Example int k = i + j;
}
public void add(String s, String t){
int k = Integer.parseInt(s) + Integer.parseInt(t);
}}
Slide 8
© Information Technology
Method Overriding
The method overriding is the process of re-defining a method: means
having two or more methods with the same arguments, but different
implementation in a child class that is already defined in the parent class.
When both parent and child classes have the same method, then that
method is said to be the overriding method.
The method overriding enables the child class to change the
implementation of the method which acquired from parent class
according to its requirement.
The benefit of overriding is:
ability to define a behavior that's specific to the subclass type which means a
subclass can implement a parent class method based on its requirement.
Slide 9
© Information Technology
Method Overriding
Rules for method overriding:
• The subclass method return type and argument list must be identical to
those of a method in the super class.
• The accessibility must not be more restrictive than original method.
• Instance methods can be overridden only if they are inherited by the
subclass.
• If a method cannot be inherited, then it cannot be overridden.
• A subclass within the same package as the instance's superclass can
override any super class method that is not declared private or final.
• Constructors cannot be overridden.
Slide 10
© Information Technology
Method Overriding
//Example of method Overriding
• In the this example, you can see that the even though b is a
class Animal{
type of Animal it runs the move method in the Dog class.
public void move(){
• The reason for this is: In compile time, the check is made on
System.out.println("Animals can move"); the reference type.
}}
• However, in the runtime, JVM figures out the object type and
class Dog extends Animal{ would run the method that belongs to that particular object.
public void move(){ • Therefore, in the this example, the program will compile
System.out.println("Dogs can walk and run"); properly since Animal class has the method move.
}} • Then, at the runtime, it runs the method specific for that
public class TestDog{ object.
public static void main(String args[]){
Animal a = new Animal(); // Animal reference and object
Animal b = new Dog(); // Animal reference but Dog object
t p u t:
Ou n move un
a.move();// runs the method in Animal class
al s ca an dr
b.move();//Runs the method in Dog class Anim can walk
}} Dogs Slide 11
© Information Technology
Method Overriding
Using the super keyword:
• When invoking a super class version of an overridden method the super keyword is used. E.g.
class Animal{
public void move(){
System.out.println("Animals can move"); } }
class Dog extends Animal{
public void move(){ Output: move
a l s ca n
Anim a l k a nd run
Super.move(); // invokes the super class method w
Dogs can
System.out.println("Dogs can walk and run"); } }
public class TestDog{
public static void main(String args[]){
Animal b = new Dog(); // Animal reference but Dog object
b.move(); //Runs the method in Dog class
}} Slide 12
© Information Technology
Polymorphism
Polymorphism means "many forms", and it occurs when we have many classes that are
related to each other by inheritance.
The polymorphism is the process of defining same method with different implementation.
That means creating multiple methods with different behaviors.
• Polymorphism in Java has two types:
• Compile time polymorphism (static binding) and
• Runtime polymorphism (dynamic binding).
• Method overloading is an example of static polymorphism, while Method overriding is an
example of dynamic polymorphism.
• An important example of polymorphism is how a parent class refers to a child class object.
• In fact, any object that satisfies more than one IS-A relationship is polymorphic in nature.
• let’s consider a class Animal and let Cat be a subclass of Animal. So, any cat IS animal. Here,
Cat satisfies the IS-A relationship for its own type as well as its super class Animal.
Slide 13
© Information Technology
Polymorphism….
class DemoOverload{
Static Polymorphism public int add(int x, int y){ //method 1
return x+y;
• In Java, static polymorphism is achieved }
through method overloading. public int add(int x, int y, int z){ //method 2
• Method overloading means there are return x+y+z;
} O utput:
several methods present in a class having 5
public int add(double x, int y){ //method 3
the same name but different return (int)x+y; 9
types/order/number of parameters. } 5
5
• At compile time, Java knows which method public int add(int x, double y){ //method 4
return x+(int)y;
to invoke by checking the method }}
signatures. So, this is called compile time Public class Test{
polymorphism or static binding. public static void main(String[] args){
DemoOverload demo=new DemoOverload();
System.out.println(demo.add(2,3)); //method 1 called
System.out.println(demo.add(2,3,4)); //method 2 called
System.out.println(demo.add(2,3.4)); //method 4 called
System.out.println(demo.add(2.5,3)); //method 3 called
Slide 14
© Information Technology
}}
Polymorphism….
class Vehicle{
Dynamic Polymorphism public void move(){
• Suppose a sub class overrides a particular System.out.println("Vehicles can move!!");
}
method of the super class. }
• Let’s say, in the program we create an class MotorBike extends Vehicle{
object of the subclass and assign it to the public void move(){
System.out.println("MotorBike can move and accelerate too!!");
super class reference. }
• Now, if we call the overridden method on }
the super class reference then the sub public class Test{
class version of the method will be called. public static void main(String[] args){
Vehicle vh=new MotorBike();
• As the method to call is determined at vh.move();// prints MotorBike can move and accelerate too!!
runtime, this is called dynamic binding or vh=new Vehicle();
late binding. vh.move();// prints Vehicles can move!!
}
Output:
}
MotorBike can move and accelerate too!!
Vehicles can move!! Slide 15
© Information Technology
Polymorphism….
Summary of polymorphic
• Every object in Java passes a minimum of two IS-A tests: one for
itself and one for Object class
Slide 17
© Information Technology
//class abstractionExample of abstract class
public class AbstractClassExample {
import java.util.*;
abstract class Shape { public static void main(String[]
int length, width, radius;
Scanner input = new Scanner(System.in); args) {
abstract void printArea(); Rectangle rec = new Rectangle();
}
rec.printArea();
class Rectangle extends Shape {
Cricle cri = new Cricle();
void printArea() {
System.out.println("*** Finding the Area of Rectangle ***"); cri.printArea();
System.out.print("Enter length: ");
length = input.nextInt(); }
System.out.print("Enter width : "); } Output:
width = input.nextInt();
*** Finding the Area of Rectangle ***
System.out.println("The area of Rectangle is: " + length * width);
Enter length: 5
}}
Enter width : 6
class Cricle extends Shape { The area of Rectangle is: 30
void printArea() {
System.out.println("\n*** Finding the Area of Cricle ***"); *** Finding the Area of Cricle ***
System.out.print("Enter Radius: "); Enter Radius: 6
radius = input.nextInt(); The area of Cricle is: 113.04s
System.out.println("The area of Cricle is: " + 3.14f * radius *
radius); Slide 18
© Information Technology
Java Interface
In java, an interface is similar to a abstract class, but it contains abstract
methods and static final variables only.
The interface in Java is another mechanism to achieve abstraction.
We may think of an interface as a completely abstract class. None of the
methods in the interface has an implementation, and all the variables in the
interface are constants.
Defining an interface is similar to that of a class. We use the keyword interface
to define an interface.
All the members of an interface are public by default.
Slide 19
© Information Technology
Java Interface…
In java, an interface is implemented by a class. The class that implements an
interface must provide code for all the methods defined in the interface.
The class uses a keyword implements to implement an interface.
A class can implement any number of interfaces.
When a class wants to implement more than one interface, we use the
implements keyword is followed by a comma-separated list of the interfaces
implemented by the class.
Slide 20
© Information Technology
Example
//java of interface
interface
interface Human {
void learn(String str);
void work();
int duration = 10;
}
ati g
lic din
s
class Programmer implements Human{
on
pp co
ve n u ut:
public void learn(String str) {
pa g
De ear utp
lo s i n
System.out.println("Learn using " +
L O
str);
}
public void work() {
System.out.println("Develop
applications");
}
}
public class HumanTest {
public static void main(String[] args) {
Programmer trainee = new
Programmer();
trainee.learn("coding");
trainee.work();
} Slide 21
} © Information Technology