chapter 5
chapter 5
OOP Concepts
1.Encapsulation
Encapsulation is one of the four fundamental OOP concepts. The other three are inheritance,
polymorphism, and abstraction.
Encapsulation in java is a process of wrapping code and data together into a single unit, for
example capsule i.e. mixed of several medicines.
It 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.
Encapsulation can be described as a protective barrier that prevents the code and data being
randomly accessed by other code defin
ed outside the class. Access to the data and code is tightly controlled by an interface.
Example:
Let us look at an example that depicts encapsulation:
1
public int getAge(){
return age;
}
The public methods are the access points to this class' fields from the outside java world.
Normally, these methods are referred as getters and setters. Therefore any class that wants to
access the variables should access them through these getters and setters.
2
2.Inheritance
Inheritance can be defined as the process where one object acquires the properties of another.
With the use of inheritance the information is made manageable in a hierarchical order.
When we talk about inheritance, the most commonly used keyword would
be extends and implements. These words would determine whether one object IS-A type of
another. By using these keywords we can make one object acquire the properties of another
object.
IS-A Relationship:
IS-A is a way of saying : This object is a type of that object. Let us see how
the extends keyword is used to achieve inheritance.
public class Animal{
}
Now, based on the above example, In Object Oriented terms, the following are true:
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 super class.
We can assure that Mammal is actually an Animal with the use of the instance operator.
Example:
public class Dog extends Mammal{
3
Animal a = new Animal();
Mammal m = new Mammal();
Dog d = new Dog();
true
true
true
Since we have a good understanding of the extends keyword let us look into how
the implements keyword is used to get the IS-A relationship.
The implements keyword is used by classes to inherit from interfaces. Interfaces can never be
extended by the classes.
Example:
public interface Animal {}
4
This would produce the following result:
true
true
true
HAS-A relationship:
These relationships are mainly based on the usage. This determines whether a certain class HAS-
A certain thing. This relationship helps to reduce duplication of code as well as bugs.
Lets us look into an example:
This shows that class Van HAS-A Speed. By having a separate class for Speed, we do not have
to put the entire code that belongs to speed inside the Van class., which makes it possible to
reuse the Speed class in multiple applications.
In Object-Oriented feature, the users do not need to bother about which object is doing the real
work. To achieve this, the Van class hides the implementation details from the users of the Van
class. So basically what happens is the users would ask the Van class to do a certain action and
the Van class will either do the work by itself or ask another class to perform the action.
A very important fact to remember is that Java supports only single inheritance. This means
that a class cannot extend more than one class. Therefore following is illegal:
However, a class can implement one or more interfaces. This has made Java get rid of the
impossibility of multiple inheritances.
Types of Inheritance
On the basis of class, there can be three types of inheritance: single, multilevel and hierarchical
in java.
In java programming, multiple and hybrid inheritance is supported through interface only. We
will learn about interfaces later.
5
Multiple inheritance is not supported in java in case of class.
When a class extends multiple classes i.e. known as multiple inheritance. For Example:
6
3.Method Overloading
If a class has multiple methods by same name but different parameters, it is known
as Method Overloading.
If we have to perform only one operation, having same name of the methods increases the
readability of the program.
Suppose you have to perform addition of the given numbers but there can be any number of
arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int) for
three parameters then it may be difficult for you as well as other programmers to understand the
behavior of the method because its name differs. So, we perform method overloading to figure
out the program quickly.
In java, Method Overloading is not possible by changing the return type of the method.
In this example, we have created two overloaded methods, first sum method performs addition of
two numbers and second sum method performs addition of three numbers.
1. class Calculation{
7
2. void sum(int a,int b)
3. {
4. System.out.println(a+b);
5. }
6. void sum(int a,int b,int c)
7. {
8. System.out.println(a+b+c);
9. }
10. public static void main(String args[]){
11. Calculation obj=new Calculation();
12. obj.sum(10,10,10);
13. obj.sum(20,20);
14. }
15. }
Output:30
40
In this example, we have created two overloaded methods that differ in data type. The first sum
method receives two integer arguments and second sum method receives two double arguments.
1. class Calculation2{
2. void sum(int a,int b)
3. {
4. System.out.println(a+b);
5. }
6. void sum(double a,double b)
7. {
8. System.out.println(a+b);
9. }
10. public static void main(String args[]){
11. Calculation2 obj=new Calculation2();
12. obj.sum(10.5,10.5);
13. obj.sum(20,20);
14.
15. }
16. }
Output:21.0
40
8
Que) Why Method Overloaing is not possible by changing the return type of method?
In java, method overloading is not possible by changing the return type of the method because
there may occur ambiguity. Let's see how ambiguity may occur:
1. class Calculation3{
2. int sum(int a,int b)
3. {
4. System.out.println(a+b);
5. }
6. double sum(int a,int b)
7. {
8. System.out.println(a+b);
9. }
10.
11. public static void main(String args[]){
12. Calculation3 obj=new Calculation3();
13. int result=obj.sum(20,20); //Compile Time Error
14.
15. }
16. }
int result=obj.sum(20,20); //Here how can java determine which sum() method should be called
Yes, by method overloading. You can have any number of main methods in a class by method
overloading. Let's see the simple example:
1. class Overloading1{
2. public static void main(int a)
3. {
4. System.out.println(a);
5. }
6.
7. public static void main(String args[]){
8. System.out.println("main() method invoked");
9. main(10);
10. }
11. }
9
Output: main() method invoked
10
One type is promoted to another implicitly if no matching data type is found. Let's understand
the concept by the figure given below:
As displayed in the above diagram, byte can be promoted to short, int, long, float or double. The
short data type can be promoted to int, long, float or double. The char data type can be promoted
to int, long, float or double and so on.
10
7. obj.sum(20,20);//now second int literal will be promoted to long
8. obj.sum(20,20,20);
9.
10. }
11. }
Output:40
60
If there are matching type arguments in the method, type promotion is not performed.
1. class OverloadingCalculation2{
2. void sum(int a,int b){System.out.println("int arg method invoked");}
3. void sum(long a,long b){System.out.println("long arg method invoked");}
4.
5. public static void main(String args[]){
6. OverloadingCalculation2 obj=new OverloadingCalculation2();
7. obj.sum(20,20);//now int arg sum() method gets invoked
8. }
9. }
If there are no matching type arguments in the method, and each method promotes similar
number of arguments, there will be ambiguity.
1. class OverloadingCalculation3{
2. void sum(int a,long b){System.out.println("a method invoked");}
3. void sum(long a,int b){System.out.println("b method invoked");}
4.
5. public static void main(String args[]){
6. OverloadingCalculation3 obj=new OverloadingCalculation3();
7. obj.sum(20,20);//now ambiguity
8. }
9. }
11
Output:Compile Time Error
4.Method Overriding
If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding.
In other words, If subclass provides the specific implementation of the method that has been
provided by one of its parent class, it is known as Method Overriding.
In this example, we have defined the run method in the subclass as defined in the parent class but
it has some specific implementation. The name and parameter of the method is same and there is
IS-A relationship between the classes, so there is method overriding.
1. class Vehicle{
2. void run() {
3. System.out.println("Vehicle is running");
12
4. }
5. }
6. class Bike2 extends Vehicle{
7. void run() { System.out.println("Bike is running safely"); }
8.
9. public static void main(String args[]){
10. Bike2 obj = new Bike2();
11. obj.run();
12. }
}
}
13
1) Method overloading is used to increase Method overriding is used to provide the specific
the readability of the program. implementation of the method that is already provided by
its super class.
2) Method overloading is performed Method overriding occurs in two classes that have IS-A
within a class. relationship.
3) In case of method overloading In case of method overriding parameter must be same.
parameter must be different.
5.Polymorphism
The word ‘polymorphism’ literally means ‘a state of having many shapes’ or ‘the capacity to
take on different forms’. When applied to object oriented programming languages like Java, it
describes a language’s ability to process objects of various types and classes through a single,
uniform interface.
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.
For instance, 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.
Note: It’s also legal to say every object in Java is polymorphic in nature, as each one passes an
IS-A test for itself and also for Object class.
Static Polymorphism:
At compile time, Java knows which method to invoke by checking the method signatures. So,
this is called compile time polymorphism or static binding. The concept will be clear from the
following example:
class DemoOverload{
14
public int add(int x, int y){ //method 1
return x+y;
return x+y+z;
return (int)x+y;
return x+(int)y;
class Test{
In the above example, there are four versions of add methods. The first method takes two
parameters while the second one takes three. For the third and fourth methods there is a change
of order of parameters. The compiler looks at the method signature and decides which method to
invoke for a particular method call at compile time.
Dynamic Polymorphism:
15
Suppose a sub class overrides a particular method of the super class. Let’s say, in the program
we create an object of the subclass and assign it to the super class reference. Now, if we call the
overridden method on the super class reference then the sub class version of the method will be
called.
class Vehicle{
}}
}}
class Test{
vh=new Vehicle();
It should be noted that in the first call to move(), the reference type is Vehicle and the object
being referenced is MotorBike. So, when a call to move() is made, Java waits until runtime to
determine which object is actually being pointed to by the reference. In this case, the object is of
the class MotorBike. So, the move() method of MotorBike class will be called. In the second call
to move(), the object is of the class Vehicle. So, the move() method of Vehicle will be called.
As the method to call is determined at runtime, this is called dynamic binding or late binding.
6.Abstraction
16
Abstraction refers to the ability to make a class abstract in OOP. An abstract class is one that
cannot be instantiated. All other functionality of the class still exists, and its fields, methods, and
constructors are all accessed in the same manner. You just cannot create an instance of the
abstract class.
If a class is abstract and cannot be instantiated, the class does not have much use unless it is
subclass. This is typically how abstract classes come about during the design phase. A parent
class contains the common functionality of a collection of child classes, but the parent class itself
is too abstract to be used on its own.
Abstract Class:
Use the abstract keyword to declare a class abstract. The keyword appears in the class
declaration somewhere before the class keyword.
/* File name : Employee.java */
public abstract class Employee
{
private String name;
private String address;
private int number;
public Employee(String name, String address, int number)
{
System.out.println("Constructing an Employee");
this.name = name;
this.address = address;
this.number = number;
}
public double computePay()
{
System.out.println("Inside Employee computePay");
return 0.0;
}
public void mailCheck()
{
System.out.println("Mailing a check to " + this.name
+ " " + this.address);
}
public String toString()
{
return name + " " + address + " " + number;
}
public String getName()
{
return name;
}
public String getAddress()
{
return address;
}
17
public void setAddress(String newAddress)
{
address = newAddress;
}
public int getNumber()
{
return number;
}
}
Notice that nothing is different in this Employee class. The class is now abstract, but it still has
three fields, seven methods, and one constructor.
When you would compile above class then you would get the following error:
18
{
System.out.println("Within mailCheck of Salary class ");
System.out.println("Mailing check to " + getName()
+ " with salary " + salary);
}
public double getSalary()
{
return salary;
}
public void setSalary(double newSalary)
{
if(newSalary >= 0.0)
{
salary = newSalary;
}
}
public double computePay()
{
System.out.println("Computing salary pay for " + getName());
return salary/52;
}
}
Here, we cannot instantiate a new Employee, but if we instantiate a new Salary object, the Salary
object will inherit the three fields and seven methods from Employee.
Constructing an Employee
Constructing an Employee
Call mailCheck using Salary reference --
Within mailCheck of Salary class
19
Mailing check to James Gosling with salary 3600.0
Abstract Methods:
If you want a class to contain a particular method but you want the actual implementation of that
method to be determined by child classes, you can declare the method in the parent class as
abstract.
The abstract keyword is also used to declare a method as abstract. An abstract method consists of
a method signature, but no method body.
Abstract method would have no definition, and its signature is followed by a semicolon, not
curly braces as follows:
The class must also be declared abstract. If a class contains an abstract method, the class must be
abstract as well.
Any child class must either override the abstract method or declare itself abstract.
A child class that inherits an abstract method must override it. If they do not, they must be
abstract and any of their children must override it.
Eventually, a descendant class has to implement the abstract method; otherwise, you would have
a hierarchy of abstract classes that cannot be instantiated.
20
{
System.out.println("Computing salary pay for " + getName());
return salary/52;
}
21
7.Interfaces
An interface is a collection of abstract methods. A class implements an interface, thereby
inheriting the abstract methods of the interface.
An interface is not a class. Writing an interface is similar to writing a class, but they are two
different concepts. A class describes the attributes and behaviors of an object. An interface
contains behaviors that a class implements.
Unless the class that implements the interface is abstract, all the methods of the interface need to
be defined in the class.
Declaring Interfaces:
The interface keyword is used to declare an interface. Here is a simple example to declare an
interface:
Example:
Let us look at an example that depicts encapsulation:
22
Interfaces have the following properties:
An interface is implicitly abstract. You do not need to use the abstract keyword when declaring
an interface.
Each method in an interface is also implicitly abstract, so the abstract keyword is not needed.
Methods in an interface are implicitly public.
Example:
/* File name : Animal.java */
interface Animal {
Implementing Interfaces:
When a class implements an interface, you can think of the class as signing a contract, agreeing
to perform the specific behaviors of the interface. If a class does not perform all the behaviors of
the interface, the class must declare itself as abstract.
A class uses the implements keyword to implement an interface. The implements keyword
appears in the class declaration following the extends portion of the declaration.
/* File name : MammalInt.java */
public class MammalInt implements Animal{
Mammal eats
Mammal travels
23
When overriding methods defined in interfaces there are several rules to be followed:
Checked exceptions should not be declared on implementation methods other than the ones
declared by the interface method or subclasses of those declared by the interface method.
The signature of the interface method and the same return type or subtype should be maintained
when overriding the methods.
An implementation class itself can be abstract and if so interface methods need not be
implemented.
Extending Interfaces:
An interface can extend another interface, similarly to the way that a class can extend another
class. The extends keyword is used to extend an interface, and the child interface inherits the
methods of the parent interface.
The following Sports interface is extended by Hockey and Football interfaces.
//Filename: Sports.java
public interface Sports
{
public void setHomeTeam(String name);
public void setVisitingTeam(String name);
}
//Filename: Football.java
public interface Football extends Sports
{
public void homeTeamScored(int points);
public void visitingTeamScored(int points);
public void endOfQuarter(int quarter);
}
//Filename: Hockey.java
public interface Hockey extends Sports
{
public void homeGoalScored();
public void visitingGoalScored();
public void endOfPeriod(int period);
public void overtimePeriod(int ot);
}
24
The Hockey interface has four methods, but it inherits two from Sports; thus, a class that
implements Hockey needs to implement all six methods. Similarly, a class that implements
Football needs to define the three methods from Football and the two methods from Sports.
The extends keyword is used once, and the parent interfaces are declared in a comma-separated
list.
For example, if the Hockey interface extended both Sports and Event, it would be declared as:
25