You are on page 1of 77

Object Oriented Programming

DR. R LAWRANCE
Director / MCA / ANJAC
lawrancer@yahoo.com
Java is pure object oriented programming or not?

Java is not considered as pure object oriented


programming language because several oops features
(like multiple inheritance, operator overloading) are not
supported by Java
Moreover we are depending on primitive data types
which are non objects. 

2
Object Oriented Programming Paradigm

3
What does the term Paradigm mean?

Derives from Latin A Way of


Paradigm Viewing the
PARADIGMA
World

4
Classes, Instances and objects
Class

Class is an abstract representation or blue print of the data and


behavior of a collection of similar entities in a system

Objects

All objects are the instances of a class

5
• A typical Java program creates many objects.
An object consists of :
• State : It is represented by attributes of an object. It
also reflects the properties of an object.
• Behavior : It is represented by methods of an object.
It also reflects the response of an object with other
objects.
• Identity : It gives a unique name to an object and
enables one object to interact with other objects.

6
Example of an object : dog

7
Declaring Objects (Also called instantiating a
class)
• When an object of a class is created, the class is said to
be instantiated.
• All the instances share the attributes and the behavior
of the class. But the values of those attributes, i.e. the
state are unique for each object.
• A single class may have any number of instances.

8
Example

9
Initializing an object
• The new operator instantiates a class by allocating
memory for a new object and returning a reference to
that memory.
• The new operator also invokes the class constructor.

10
Getter and Setter
• The get method returns the variable value, and the set
method sets the value.
public class SimpleGetterAndSetter {
private int number;

public int getNumber() {


return this.number;
}

public void setNumber(int num) {


this.number = num;
}
}

The class declares a private variable, number. Since number is private, code
from outside this class cannot access.
11
SimpleGetterAndSetter obj = new SimpleGetterAndSetter();
obj.number = 10;

// compiler error, since number is private

Instead, the outside code have to invoke the getter,


getNumber() and the setter, setNumber() in order to read or
update the variable, for example:

SimpleGetterAndSetter obj = new SimpleGetterAndSetter();

obj.setNumber(10); // OK

12
Why getter and setter?

• By using getter and setter, the programmer can control


how his important variables are accessed and updated in
a correct manner, such as changing value of a variable
within a specified range.
• Consider the following code of a setter method:
public void setNumber(int num) {
if (num < 10 || num > 100) {
throw new IllegalArgumentException();
}
this.number = num;
}
That ensures the value of number is always set between 10 and
100. Suppose the variable number can be updated directly, the
caller can set any arbitrary value to it:

obj.number = 3;
13
A getter method is the only way for the outside world reads the
variable’s value:

public int getNumber() {


return this.number;
}

14
• When a variable is hidden by private modifier and can be accessed
only through getter and setter, it is encapsulated. 
• Encapsulation is one of the fundamental principles in object-
oriented programming (OOP), thus implementing getter and setter is
one of ways to enforce encapsulation in program’s code.
• Some frameworks such as Hiberate, Spring, Struts… can inspect
information or inject their utility code through getter and setter.
• So providing getter and setter is necessary when integrating your
code with such frameworks.

15
Naming convention for getter and setter

• The naming scheme of setter and getter should follow


Java bean naming convention as follows:
– getXXX() and setXXX()
where XXX is name of the variable.
For example with the following variable name:
private String name;
then the appropriate setter and getter will be:
public void setName(String name) { }

public String getName() { }

16
Naming Convention
Variable Getter method Setter method
declaration
     
int quantity int getQuantity() void setQuantity(int
  qty)
 

     
string firstName String getFirstName() void setFirstName(String fname)
 

     
Date birthday Date getBirthday() void setBirthday(Date bornDate)
 

     
boolean rich boolean isRich() void setRich(Boolean rich)
  boolean getRich()
17
public String firstName;

public void setFirstName(String fname) {


this.firstName = fname;
}

public String getFirstName() {


return this.firstName;
}

The variable firstName is declared as public, so it can be accessed


using dot (.) operator directly, making the setter and getter useless.
Workaround for this case is using more restricted access modifier
such as protected and private.

18
public int getAge()
public class Dog
{
{ return age;
// Instance Variables }
private String name; public String getColor()
private String breed; {
private int age; return color;
private String color; }
public String getName()
{
return name;
}
public String getBreed()
{
return breed;
} 19
   public void setName(String
name) public static void main(String[] args)
   { {
      this.name = name;
   } Dog tuffy = new Dog();
public void setBreed(String tuffy.setName(“Tuffy”);
breed)
tuffy.setBreed(“Rajapalyam”);
{
this.breed=breeda tuffy.setAge(5);
} tuffy.setColor(“White”);
   public void setAge( int age)
   { System.out.println(“Hi My Name is:
      this.age = age; “+tuffy.getName()+” My Breed is: “+
   }
tuffy.getBreed()+” My age is: “+getAge()
public void setColor(String
color) +”My Color is: “+getColor());
{ }
this.color=color;
}
}
} 20
21
Challenge - 1
• Write a program to show the student details
using setter and getter methods.

22
Few of the pillars of object oriented
approach
Keeping the Ability of a class to
design and inherit some data
ABSTRACTION INHERITANCE and behavior from
execution
isolated other related
classes

The property by
Controlling and
which different
managing the INFORMATION POLYMORPHISM objects respond
accessibility and HIDING
differently to the
visibility
same method

Tasks get done


Keeping the
through objects
data and ENCAPSULATION MESSAGE
sending messages to
operations PASSING
other objects
together
requesting them to
perform a task

23
Message Passing

24
What does a procedure call do?
• answer = sum(a,b)
Procedure name

All information on binding Early Binding


procedure name to procedure
body known at compile time

Procedure body or
Code fragment for
sum

After executing the procedure


body the control is returned to
the caller.
25
What does message passing do?
Message with arguments
Sender Object Receiver Object (A)
(Teacher) (Student)

Even though the object sends the message to Object A, the ultimate
receiver of message is not known until runtime

So, the Method to invoke for execution will not be known till runtime.

This is called “late binding”, since the actual code of the method to be
executed is known only at runtime.

Object A can choose to


Object A can choose to Object A can choose to
carry out part of tasks using
carry out all tasks carry out all tasks using
its own methods & other
requesting other objects its own methods.
tasks requesting other
26
objects.
Encapsulation
Dictionary meaning of encapsulation

To place in or as if in a capsule

Keeping the
data and
operations
together

27
Tightly encapsulated

If every data member is private then it is tightly coupled


Public class Account
{
Private double balance;
Public double getBalance()
}

Class A Class A
{ {
public int x = 10; Private int x = 10;
} }
Class b extends A Class b extends A
{ {
private int y ; Public int y ;
} }
Class C extends A Class C extends A
{ {
Private int z=30; Private int z=30;
} }
28
Encapsulation in context of OO Approach

The outside view The Inside view

Invisible implementation
Visible Interface

Data Items

PUSH
Implementation of
Push, Pop
POP

Data and methods of


objects are bundled
together as in capsule

29
Information Hiding

30
Data/Information Hiding
• Our internal data should not go out directly or others could not access our
data
• How do we achieve this?
• Every data member should provide as private we can do this

Recommended
public class Account modifier
{
private double balance;

public double getBalance()
{
}
• In Java default modifier is default
Advantage
• Security

31
Access Modifiers In Java 

32
Encapsulation & Information Hiding

33
Inheritance

34
IS-A Relationship(inheritance)

• Also known as inheritance.


• By using "extends" keywords we can implement IS-A
relationship.
• The main advantage of IS-A relationship is reusability.

Example:
class Parent
{
public void methodOne()
{ }
}
class Child extends Parent
{
public void methodTwo()
{ }
}

35
Example:
class Parent
{
public void methodOne()
{ }
}
class Child extends Parent
{
public void methodTwo()
{ }
}

36
37
Conclusion
• Whatever the parent has by default available to the child but
whatever the child has by default not available to the parent.
• Hence on the child reference we can call both parent and child
class methods. But on the parent reference we can call only
methods available in the parent class and we can't call child
specific methods.
• Parent class reference can be used to hold child class object but
by using that reference we can call only methods available in
parent class and child specific methods we can't call.
• Child class reference cannot be used to hold parent class object.

38
• Example:
• The common methods which are required for housing
loan, vehicle loan, personal loan and education loan we
can define into a separate class in parent class loan.
• So that automatically these methods are available to
every child loan class.

Example: class Loan


{ //common methods which are required for any type of loan.
}
class HousingLoan extends Loan
{ //Housing loan specific methods.
}
class EducationLoan extends Loan
{ //Education Loan specific methods.
}

39
• For all java classes the most commonly required functionality
is define inside object class hence object class acts as a root for
all java classes.
• For all java exceptions and errors the most common required
functionality defines inside Throwable class hence Throwable
class acts as a root for exception hierarchy.

40
class Employee
{
float sal=60000;
}
class Main extends Employee
{
float b=1500;
float temp= sal + b;
public static void main(String args[])
{
Main ob=new Main();
System.out.println("Salary amount is:"+ob.sal);
System.out.println(" Extra Bonous is:"+ob.temp);
}
}

41
public class Main extends Calc {
class Calc{
int mul(int xx , int yy)
int sum(int i , int j)
{
{
return xx*yy;
return i+j;
}
}
int divide(int xx , int yy)
int subract(int i , int j)
{
{
return xx/yy;
return i-j;
}
}
}
public static void main(String args[]) {
Main c= new Main();
System.out.println(c.sum(2,2));
System.out.println(c.subract(2,6));
System.out.println(c.mul(8,9));
System.out.println(c.divide(2,2));
}
}

42
Multiple inheritance
• Having more than one Parent class at the same level is
called multiple inheritance.
• Example: 

43
• Any class can extends only one class at a time and can't
extends more than one class simultaneously hence java
won't provide support for multiple inheritance.
• Example: 

44
• But an interface can extends any no. of interfaces at a time
hence java provides support for multiple inheritance through
interfaces.
• Example:

45
• If our class doesn't extends any other class then only our
class is the direct child class of object.
• Example:

46
• If our class extends any other class then our class is not
direct child class of object, It is indirect child class of
object , which forms multilevel inheritance.

47
Why java won't provide support for multiple
inheritance?

• There may be a chance of raising ambiguity problems.

48
Why ambiguity problem won't be there in interfaces?
• Interfaces having dummy declarations and they won't have
implementations hence no ambiguity problem.

49
Cyclic inheritance 

• Cyclic inheritance is not allowed in java


• Example 1: 

• Example 2:
 

50
HAS-A relationship

• HAS-A relationship
• HAS-A relationship is also known as composition (or)
aggregation.
• There is no specific keyword to implement HAS-A
relationship but mostly we can use new operator.
• The main advantage of HAS-A relationship is reusability.
Example:
class Engine
{
//engine specific functionality
}
class Car
{
Engine e=new Engine();
//........................;
}
51
Abstraction
Keeping the design and execution isolated

Simplified representation of reality

MAP is an abstraction or
simplified representation of
what it models

52
Abstraction focuses the outside view of an
object
The outside The Inside
view view

Visible Interface
As a bounded Array

PUSH

POP

What user What


sees… implementer
sees…
53
Abstraction and Encapsulation are
complementary concepts

Abstraction Encapsulation
Focuses on the Focuses on the
observable implementation
behavior of an behavior of an
object object

54
Abstraction..
 AKA – Central Point, outline, Top level information , Not
detailed information
 Hide internal information – Only services are highlighted
 Ex: ATM card – enter PIN – withdraw amount
(Internal process is not known like query, server, db, lang)
Advantages
 Security (outsiders do not aware about internal process)
(Wherever hiding there is security)
 Enhancement – without affecting the services we can perform
any changes in the internal system
 Eazyness – without knowing the internal code we can use
services
 By using abstract classes & interfaces we can implement
abstraction
55
56
Example

Example of abstract class

abstract class A{}  

Abstract Method in Java

A method which is declared as abstract and does not have


implementation is known as an abstract method.

Example of abstract method

abstract void printStatus();//no method body and abstract  

57
abstract class Bank{
abstract int getRateOfInterest();
}
class SBI extends Bank{
int getRateOfInterest(){return 7;}
}
class TMB extends Bank{
int getRateOfInterest(){return 8;}
}

class TestBank{
public static void main(String args[]){
Bank b;
b=new SBI();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
b=new TMB();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
}}
58
For any abstract java class we are not allowed to create an object i.e., for abstract
class instantiation is not possible. 

abstract class Test {


public static void main(String args[])
{
// Try to create an object
Test t = new Test();
}
}

Output:

Compile time error. Test is abstract;


cannot be instantiated Test t=new Test();

59
An abstract class can contain constructors in Java. And a constructor of
abstract class is called when an instance of an inherited class is created.

abstract class Base {


Base()
{
System.out.println("Base Constructor Called");
}
abstract void fun();
}
class Derived extends Base {
Derived()
{
System.out.println("Derived Constructor Called");
}
}
class Main {
public static void main(String args[])
{
Derived d = new Derived();
}
60
}
In Java, we can have an abstract class without any abstract method. This
allows us to create classes that cannot be instantiated but can only be
inherited.

// An abstract class without any abstract method


abstract class Base {
void fun() { System.out.println("Base fun() called"); }
}

class Derived extends Base {


}

class Main {
public static void main(String args[])
{
Derived d = new Derived(); Output
d.fun();
}
} Base fun() called

61
Interface
• An interface in Java is a blueprint of a class.
It has static constants and abstract methods.

62
How to declare an interface?

• An interface is declared by using the interface keyword. It provides


total abstraction; means all the methods in an interface are declared
with the empty body, and all the fields are public, static and final by
default

interface <interface_name>{

// declare constant fields


// declare methods that abstract
// by default.
}

63
Internal addition by the compiler
• The Java compiler adds public and abstract keywords before
the interface method. Moreover, it adds public, static and
final keywords before data members.

64
Polymorphism
• Same name with different forms is the concept of
polymorphism.

 Example

 We can use the parent reference to hold any child objects.

 We can use the same List reference to hold ArrayList object,


LinkedList object, Vector object, or Stack object.

» List l=new ArrayList();


» List l=new LinkedList();
» List l=new Vector();
» List l=new Stack();
3 Pillars of OOPS

1) Inheritance talks about reusability. 


2) Polymorphism talks about flexibility.
3) Encapsulation talks about security.
Overloading
Two methods are said to be overloaded if and only if both having the same name
but different argument types.

In java we can take multiple methods with the same name and different
argument types.

Example:

• Having the same name and different argument


types is called method overloading.
• All these methods are considered as overloaded
methods.
• Having overloading concept in java reduces
complexity of the programming.
Example
class Test
{ public void methodOne()
{ System.out.println("no-arg method");
}
public void methodOne(int i)
{ System.out.println("int-arg method"); //overloaded metho
}
public void methodOne(double d)
{ System.out.println("double-arg method");
}
public static void main(String[] args)
{ Test t=new Test();
t.methodOne();//no-arg method
t.methodOne(10);//int-arg method
t.methodOne(10.5);//double-arg method
} }
Overriding
• Whatever the Parent has by default available to the Child
through inheritance, if the Child is not satisfied with
Parent class method implementation then Child is allow
to redefine that Parent class method in Child class in its
own way this process is called overriding.
• The Parent class method which is overridden is called
overridden method.
• The Child class method which is overriding is called
overriding method. 
class Parent
{
public void property()
{
System.out.println("cash+land+gold");
}
public void marry()
{
System.out.println("subbalakshmi"); //overridden method
}
}
class Child extends Parent
{ //overriding
public void marry()
{
System.out.println("3sha/9tara/anushka"); //overriding method
}
}
class Test
{
public static void main(String[] args)
{
Parent p=new Parent();
p.marry();
Child c=new Child();
c.marry();
Parent p1=new Child();
class Parent
{
public void property()
{
System.out.println("cash+land+gold");
}
public void marry()
{
System.out.println("subbalakshmi"); //overridden method
}
}
class Child extends Parent
{ //overriding
public void marry()
{
System.out.println("3sha/4me/9tara/anushka"); //overriding method
}
}
class Test
{
public static void main(String[] args)
{
Parent p=new Parent();
p.marry();//subbalakshmi(parent method)
Child c=new Child();
c.marry();//Trisha/nayanatara/anushka(child method)
Parent p1=new Child();
p1.marry();//Trisha/nayanatara/anushka(child method)
}
}
Conclusion
• In overriding method resolution is always takes care by
JVM based on runtime object hence overriding is also
considered as runtime polymorphism or dynamic
polymorphism or late binding.
• The process of overriding method resolution is also
known as dynamic method dispatch.
• Note: In overriding runtime object will play the role and
reference type is dummy.
• In overriding method names and arguments must be
same. That is method signature must be same
A bank maintains two kinds of accounts – Savings account and Current
account. The
savings account provides simple interest, deposit and withdrawal
facilities. The current account only provides deposit and withdrawal
facilities. Current account holders should also maintain minimum
balance. If balance falls below minimum level a service charge is
imposed. Create an abstract class Account that stores customer name,
account number type of account and abstract methods. From this derive
the classes Curr_Account (double balance, double min_bal, double
serviceCharge / penalty) and and Sav_Account (double balance). Include
the necessary methods in order to achieve the following:
a. Define parameterized constructor in a class hierarchy.
b. Allow deposit and update the balance.
c. Display the balance.
d. Compute interest and add to balance.
e. Permit withdrawal and update the balance (check for minimum
balance).
f. Apply polymorphism if required for methods in class hierarchy.
It's a lie to think you're not good

enough. It's a lie to think you're not


worth anything.”
― Nick Vujicic
You shouldn’t work for someone else,
you should work for yourself

You might also like