Lecture 8

Download as pdf or txt
Download as pdf or txt
You are on page 1of 31

Lecture 8:

OOP Basics 3
Abstraction, Encapsulation, Inheritance, Polymorphism,
Abstract Class and Methods, Interfaces in Java

Object Oriented Programming


1
Introduction
• Java is an object oriented language because it provides the features to
implement an object oriented model. These features includes
– Abstraction
– Encapsulation
– Inheritance
– and polymorphism.

• OOPS is about developing an application around its data, i.e. objects


which provides the access to their properties and the possible operations
in their own way.

2
Abstraction
• One of the most fundamental concept of OOPs is Abstraction.

• Abstraction is a process where you show only “relevant” data and “hide”
unnecessary details of an object from the user.

• For example, when you login to your Amazon account online, you enter
your user_id and password and press login, what happens when you
press login, how the input data sent to amazon server, how it gets verified
is all abstracted away from the you.

• Another example of abstraction: A car in itself is a well-defined object,


which is composed of several other smaller objects like a gearing system,
steering mechanism, engine, which are again have their own subsystems.
But for humans car is a one single object, which can be managed by the
help of its subsystems, even if their inner details are unknown.

3
Encapsulation
• Encapsulation is:
– Binding the data with the code that manipulates it.
– It keeps the data and the code safe from external interference

• Looking at the example of a power steering mechanism of a car. Power


steering of a car is a complex system, which internally have lots of
components tightly coupled together, they work synchronously to turn the
car in the desired direction. It even controls the power delivered by the
engine to the steering wheel. But to the external world there is only one
interface is available and rest of the complexity is hidden. Moreover, the
steering unit in itself is complete and independent. It does not affect the
functioning of any other mechanism.

4
Encapsulation
• Similarly, same concept of encapsulation can be applied to code.
Encapsulated code should have following characteristics:

– Everyone knows how to access it.


– Can be easily used regardless of implementation details.
– There shouldn’t any side effects of the code, to the rest of the
application.
– The idea of encapsulation is to keep classes separated and prevent
them from having tightly coupled with each other.

• A example of encapsulation is the class of java.util.Hashtable. User only


knows that he can store data in the form of key/value pair in a Hashtable
and that he can retrieve that data in the various ways. But the actual
implementation like, how and where this data is actually stored, is hidden
from the user. User can simply use Hashtable wherever he wants to store
Key/Value pairs without bothering about its implementation.

5
Encapsulation
• Encapsulation simply means binding object state(fields) and
behaviour(methods) together. If you are creating class, you are doing
encapsulation

• The whole idea behind encapsulation is to hide the implementation details


from users. If a data member is private it means it can only be accessed
within the same class. No outside class can access private data member
(variable) of other class.

• However if we setup public getter and setter methods to update (for


example void setEmpName(String newValue))and read (for example
String getEmpName()) the private data fields then the outside class can
access those private data fields via public methods.

• This way data can only be accessed by public methods thus making the
private fields and their implementation hidden for outside classes. That’s
why encapsulation is known as data hiding. Lets see an example to
understand this concept better. 6
Encapsulation
class EncapsulationDemo{
private String empName;

public String getEmpName(){


return empName;
}
public void setEmpName(String newValue){
empName = newValue;
}
}
public class EncapsTest{
public static void main(String args[]){
EncapsulationDemo obj = new EncapsulationDemo();
obj.setEmpName(“Super Mario");
System.out.println("Employee Name: " + obj.getEmpName());
}
}

Output:
Employee Name: Super Mario

7
Inheritance
• The process by which one class acquires the properties(data members)
and functionalities(methods) of another class is called inheritance.

• The aim of inheritance is to provide the reusability of code so that a class


has to write only the unique features and rest of the common properties
and functionalities can be extended from the another class.

• Child Class:
– The class that extends the features of another class is known as child
class, sub class or derived class.

• Parent Class:
– The class whose properties and functionalities are used(inherited) by
another class is known as parent class, super class or Base class.

8
Inheritance
• Inheritance is the mechanism by which an object acquires the some/all
properties of another object.
• It supports the concept of hierarchical classification.

• For example: Car is a four wheeler vehicle so assume that we have a class
FourWheeler and a sub class of it named Car. Here Car acquires the
properties of a class FourWheeler. Other classifications could be a jeep, lorry,
van etc.

• FourWheeler defines a class of vehicles that have four wheels, and specific
range of engine power, load carrying capacity etc. Car (termed as a sub-class)
acquires these properties from FourWheeler, and has some specific
properties, which are different from other classifications of FourWheeler, such
as luxury, comfort, shape, size, usage etc.

• A car can have further classification such as an open car, small car, big car
etc, which will acquire the properties from both Four Wheeler and Car, but will
still have some specific properties. This way the level of hierarchy can be
extended to any level.
9
Inheritance
• Inheritance is a process of defining a new class based on an existing class
by extending its common data members and methods.
• Inheritance allows us to reuse of code, it improves reusability in your java
application.
• Note: The biggest advantage of Inheritance is that the code that is already
present in base class need not be rewritten in the child class.
• This means that the data members(instance variables) and methods of the
parent class can be used in the child class as.

• Syntax: Inheritance in Java


• To inherit a class we use extends keyword. Here class XYZ is child class
and class ABC is parent class. The class XYZ is inheriting the properties
and methods of ABC class.

class XYZ extends ABC


{
}
10
Polymorphism
• Polymorphism is one of the OOPs feature that allows us to perform a
single action in different ways.

• For example, lets say we have a class Animal that has a method sound().
Since this is a generic class so we can’t give it a implementation like:
Roar, Meow, Oink etc. We had to give a generic message.

public class Animal{


...
public void sound(){
System.out.println("Animal is making a sound");
}
}

11
Polymorphism
• Now lets say we two subclasses of Animal class: Horse and Cat that extends (see
Inheritance) Animal class. We can provide the implementation to the same method
like this:

public class Horse extends Animal{


...
@Override
public void sound(){
System.out.println("Neigh");
}
}

• and
public class Cat extends Animal{
...
@Override
public void sound(){
System.out.println("Meow");
}
}
12
Polymorphism
• As you can see that although we had the common action for all
subclasses sound() but there were different ways to do the same action.

• This is a perfect example of polymorphism (feature that allows us to


perform a single action in different ways). It would not make any sense to
just call the generic sound() method as each Animal has a different sound.

• Thus we can say that the action this method performs is based on the type
of object.

13
Polymorphism
• Polymorphism is the capability of a method to do different things based on
the object that it is acting upon.

• In other words, polymorphism allows you define one interface and have
multiple implementations. As we have seen in the above example that we
have defined the method sound() and have the multiple implementations
of it in the different-2 sub classes.

• Which sound() method will be called is determined at runtime so the


example we gave above is a runtime polymorphism example.

• Types of polymorphism
– 1. Method Overloading in Java
– 2. Method Overriding in Java

14
Method Overloading
• Method Overloading is a feature that allows a class to have more than one
method having the same name, if their argument lists are different.
• It is similar to constructor overloading in Java, that allows a class to have
more than one constructor having different argument lists.

• let’s get back to the point, when I say argument list it means the
parameters that a method has:

• For example the argument list of a method add(int a, int b) having two
parameters is different from the argument list of the method add(int a, int
b, int c) having three parameters.

15
Method Overloading
• Three ways to overload a method
• In order to overload a method, the argument lists of the methods must
differ in either of these:

1. Number of parameters.
add(int, int)
add(int, int, int)

2. Data type of parameters.


add(int, int)
add(int, float)

3. Sequence of Data type of parameters.


add(int, float)
add(float, int)

16
Method Overriding
• Declaring a method in sub class which is already present in parent class
is known as method overriding. Overriding is done so that a child class
can give its own implementation to a method which is already provided by
the parent class. In this case the method in parent class is called
overridden method and the method in child class is called overriding
method.

• Method Overriding Example


• Lets take a simple example to understand this. We have two classes: A
child class Boy and a parent class Human. The Boy class extends Human
class. Both the classes have a common method void eat(). Boy class is
giving its own implementation to the eat() method or in other words it is
overriding the eat() method.

• The purpose of Method Overriding is clear here. Child class wants to give
its own implementation so that when it calls this method, it prints Boy is
eating instead of Human is eating.
17
Method Overriding
class Human{
//Overridden method
public void eat()
{
System.out.println("Human is eating");
}
}
class Boy extends Human{
//Overriding method
public void eat(){
System.out.println("Boy is eating");
}
public static void main( String args[]) {
Boy obj = new Boy();
//This will call the child class version of eat()
obj.eat();
}
}

• Output: 18
Boy is eating
Abstract Class & Abstract Method
• A class that is declared using “abstract” keyword is known as abstract
class. It can have abstract methods(methods without body) as well as
concrete methods (regular methods with body). A normal class(non-
abstract class) cannot have abstract methods.

• An abstract class can not be instantiated, which means you are not
allowed to create an object of it.

• Why we need an abstract class?


• Lets say we have a class Animal that has a method sound() and the
subclasses of it like Dog, Lion, Horse, Cat etc. Since the animal sound
differs from one animal to another, there is no point to implement this
method in parent class. This is because every child class must override
this method to give its own implementation details, like Lion class will say
“Roar” in this method and Dog class will say “Woof”.

19
Abstract Class & Abstract Method
• So when we know that all the animal child classes will and should override
this method, then there is no point to implement this method in parent
class. Thus, making this method abstract would be the good choice as by
making this method abstract we force all the sub classes to implement this
method( otherwise you will get compilation error), also we need not to give
any implementation to this method in parent class.

• Since the Animal class has an abstract method, you must need to declare
this class abstract.

• Now each animal must have a sound, by making this method abstract we
made it compulsory to the child class to give implementation details to this
method. This way we ensures that every animal has a sound.

20
Abstract Class & Abstract Method
• Abstract class Example
//abstract parent class • Output:
abstract class Animal{
Woof
//abstract method
public abstract void sound();
}
//Dog class extends Animal class
public class Dog extends Animal{

public void sound(){


System.out.println("Woof");
}
public static void main(String args[]){
Animal obj = new Dog();
obj.sound();
}
}

• Hence for such kind of scenarios we generally declare the class as


abstract and later concrete classes extend these classes and override the
methods accordingly and can have their own methods as well. 21
Abstract Class & Abstract Method
• A class which is declared as abstract is known as an abstract class. It can
have abstract and non-abstract methods. It needs to be extended and its
method implemented. It cannot be instantiated.

• Points to Remember
– An abstract class must be declared with an abstract keyword.
– It can have abstract and non-abstract methods.
– It cannot be instantiated.
– It can have constructors and static methods also.
– It can have final methods which will force the subclass not to change the body
of the method.

22
Interface
• Interface looks like a class but it is not a class. An interface can have
methods and variables just like the class but the methods declared in
interface are by default abstract (only method signature, no body, see:
Java abstract method). Also, the variables declared in an interface are
public, static & final by default. We will cover this in detail, later in this
guide.

• What is the use of interface in Java?


• As mentioned above they are used for full abstraction. Since methods in
interfaces do not have body, they have to be implemented by the class
before you can access them. The class that implements interface must
implement all the methods of that interface. Also, java programming
language does not allow you to extend more than one class, However you
can implement more than one interfaces in your class.

23
Interface
• Syntax:
• Interfaces are declared by specifying a keyword “interface”. E.g.:

interface MyInterface
{
/* All the methods are public abstract by default
* As you see they have no body
*/
public void method1();
public void method2();
}

24
Example of an Interface in Java
• This is how a class implements an interface. It has to provide the body of
all the methods that are declared in interface or in other words you can
say that class has to implement all the methods of interface.

• Do you know? class implements interface but an interface extends another


interface.

interface MyInterface
{
/* compiler will treat them as:
* public abstract void method1();
* public abstract void method2();
*/
public void method1();
public void method2();
}

25
Example of an Interface in Java
class Demo implements MyInterface
{
/* This class must have to implement both the • Output:
abstract methods else you will get compilation error */ implementation of method1

public void method1()


{
System.out.println("implementation of method1");
}
public void method2()
{
System.out.println("implementation of method2");
}

public static void main(String arg[])


{
MyInterface obj = new Demo();
obj.method1();
}
26
}
Why use Java interface?
• There are mainly three reasons to use interface. They are given below.

• It is used to achieve abstraction.


• By interface, we can support the functionality of multiple inheritance.
• It can be used to achieve loose coupling.

27
The relationship between classes and
interfaces
• As shown in the figure given below, a class extends another class, an
interface extends another interface, but a class implements an interface.

Example in slide 21 slide 26 slide 29

28
Example of an Interface extends Interface
interface Inf1{
public void method1();
}
interface Inf2 extends Inf1 {
public void method2();
}
public class Demo implements Inf2{
/* Even though this class is only implementing the
* interface Inf2, it has to implement all the methods
* of Inf1 as well because the interface Inf2 extends Inf1
*/
public void method1(){
System.out.println("method1");
}
public void method2(){
System.out.println("method2");
}
public static void main(String args[]){
Inf2 obj = new Demo();
obj.method2();
}
}

29
Multiple inheritance in Java by
interface
• If a class implements multiple interfaces, or an interface extends multiple
interfaces, it is known as multiple inheritance.

30
Example class implements multiple
interfaces
interface Printable{
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}

public static void main(String args[]){


A7 obj = new A7();
obj.print();
obj.show();
}
}

Output: Hello
Welcome
31

You might also like