SlideShare a Scribd company logo
1 of 27
Download to read offline
•
•
•
•

https://www.facebook.com/Oxus20

oxus20@gmail.com

Classes and Objects
Encapsulation
Inheritance
Polymorphism

Object
Oriented
Programming
Abdul Rahman Sherzad
Agenda
» Object Oriented Programming
» Definition and Demo
˃ Class
˃ Object
˃ Encapsulation (Information Hiding)
˃ Inheritance
˃ Polymorphism
˃ The instanceof Operator
2

https://www.facebook.com/Oxus20
Object Oriented Programming (OOP)
» OOP makes it easier for programmers to structure
and form software programs.
» For the reason that individual objects can be
modified without touching other aspects of the
program.
˃ It is also easier to update and modify programs written in object-oriented
languages.

» As software programs have grown larger over the
years, OOP has made developing these large
programs more manageable.
3

https://www.facebook.com/Oxus20
Class Definition
» A class is kind of a blueprint or template that refer to the methods and
attributes that will be in each object.
» BankAccount is a blueprint as follow
˃ State / Attributes
+ Name
+ Account number
+ Type of account
+ Balance
˃ Behaviors / Methods
+ To assign initial value
+ To deposit an account
+ To withdraw an account
+ To display name, account number & balance.
Now you, me and others can have bank accounts (objects / instances) under the above BankAccount
blueprint where each can have different account name, number and balance as well as I can deposit
500USD, you can deposit 300USD, as well as withdraw, etc.
https://www.facebook.com/Oxus20

4
BankAccount Class Example
public class BankAccount {
// BankAccount attributes
private String accountNumber;
private String accountName;
private double balance;
// BankAccount methods
// the constructor
public BankAccount(String accNumber, String accName) {
accountNumber = accNumber;
accountName = accName;
balance = 0;
}
5

https://www.facebook.com/Oxus20
BankAccount Class Example (contd.)
// methods to read the attributes
public String getAccountName() {
return accountName;
}
public String getAccountNumber() {
return accountNumber;
}
public double getBalance() {
return balance;
}

6

https://www.facebook.com/Oxus20
BankAccount Class Example (contd.)
// methods to deposit and withdraw money
public boolean deposit(double amount) {
if (amount > 0) {
balance = balance + amount;
return true;
} else {
return false;
}
}
public boolean withdraw(double amount) {
if (amount > balance) {
return false;
} else {
balance = balance - amount;
return true;
}
}
7

}
https://www.facebook.com/Oxus20
Object Definition
» An object holds both variables and methods; one object
might represent you, a second object might represent
me.
» Consider the class of Man and Woman
˃ Me and You are objects

» An Object is a particular instance of a given class. When
you open a bank account; an object or instance of the
class BankAccount will be created for you.
https://www.facebook.com/Oxus20

8
BankAccount Object Example
BankAccount absherzad = new BankAccount("20120",
"Abdul Rahman Sherzad");

» absherzad is an object of BankAccount with Account Number of

"20120" and Account Name of "Abdul Rahman Sherzad".
» absherzad object can deposit, withdraw as well as check the

balance.
9

https://www.facebook.com/Oxus20
BankAccount Demo
public class BankAccountDemo {
public static void main(String[] args) {
BankAccount absherzad = new BankAccount("20120",

"Abdul Rahman Sherzad");

absherzad.deposit(500);
absherzad.deposit(1500);
System.out.println("Balance is: " + absherzad.getBalance()); //2000

absherzad.withdraw(400);
System.out.println("Balance is: " + absherzad.getBalance()); //1600
}
}
10

https://www.facebook.com/Oxus20
Encapsulation Definition
» Encapsulation is the technique of making the class
attributes private and providing access to the attributes
via public methods.
» If attributes are declared private, it cannot be accessed
by anyone outside the class.
˃ For this reason, encapsulation is also referred to as Data Hiding (Information Hiding).

» Encapsulation can be described as a protective barrier
that prevents the code and data corruption.
» The main benefit of encapsulation is the ability to
modify our implemented code without breaking the
code of others who use our code.
https://www.facebook.com/Oxus20

11
Encapsulation Benefit Demo
public class EncapsulationDemo {
public static void main(String[] args) {
BankAccount absherzad = new BankAccount("20120",
absherzad.deposit(500);

"Abdul Rahman Sherzad");

// Not possible because withdraw() check the withdraw amount with balance
// Because current balance is 500 and less than withdraw amount is 1000

absherzad.withdraw(1000); // Encapsulation Benefit

// Not possible because class balance is private
// and not accessible directly outside the BankAccount class
absherzad.balance = 120000; // Encapsulation Benefit
}
}
12

https://www.facebook.com/Oxus20
Inheritance Definition
» inheritance is a mechanism for enhancing existing
classes
˃ Inheritance is one of the other most powerful techniques of object-oriented
programming
˃ Inheritance allows for large-scale code reuse

» with inheritance, you can derive a new class from an

existing one
˃ automatically inherit all of the attributes and methods of the existing class
˃ only need to add attributes and / or methods for new functionality
13

https://www.facebook.com/Oxus20
BankAccount Inheritance Example
» Savings Account is a
bank account with
interest
» Checking Account is a

bank account with
transaction fees
14

https://www.facebook.com/Oxus20
Specialty Bank Accounts
» now we want to implement SavingsAccount and
CheckingAccount
˃ A SavingsAccount is a bank account with an associated interest
rate, interest is calculated and added to the balance periodically
˃ could copy-and-paste the code for BankAccount, then add an
attribute for interest rate and a method for adding interest

˃ A CheckingAccount is a bank account with some number of free
transactions, with a fee charged for subsequent transactions
˃ could copy-and-paste the code for BankAccount, then add an
attribute to keep track of the number of transactions and a
method for deducting fees
15

https://www.facebook.com/Oxus20
Disadvantages of the copy-and-paste Approach

» tedious and boring work
» lots of duplicate and redundant code
˃ if you change the code in one place, you have to change it
everywhere or else lose consistency (e.g., add customer

name to the bank account info)

» limits polymorphism (will explain later)
16

https://www.facebook.com/Oxus20
SavingsAccount class (inheritance provides a better solution)
» SavingsAccount can be defined to be a special kind of BankAccount
» Automatically inherit common features (balance, account #, account name,
deposit, withdraw)
» Simply add the new features specific to a SavingsAccount
» Need to store interest rate, provide method for adding interest to the
balance
» General form for inheritance:
public class DERIVED_CLASS extends EXISTING_CLASS {
ADDITIONAL_ATTRIBUTES
ADDITIONAL_METHODS
}

17

https://www.facebook.com/Oxus20
SavingsAccount Class
public class SavingsAccount extends BankAccount {
private double interestRate;
public SavingsAccount(String accNumber, String accName, double rate) {

super(accNumber, accName);
interestRate = rate;
}
public void addInterest() {
double interest = getBalance() * interestRate / 100;
this.deposit(interest);
}
}
18

https://www.facebook.com/Oxus20
SavingsAccount Demo
public class SavingsAccountDemo {
public static void main(String[] args) {
SavingsAccount saving = new SavingsAccount("20120",
"Abdul Rahman Sherzad", 10);
// deposit() is inherited from BankAccount (PARENT CLASS)

saving.deposit(500);
// getBalance() is also inherited from BankAccount (PARENT CLASS)

System.out.println("Before Interest: " + saving.getBalance());
saving.addInterest();
System.out.println("After Interest: " + saving.getBalance());
}
}

19

https://www.facebook.com/Oxus20
CheckingAccount Class
public class CheckingAccount extends BankAccount {
private int transactionCount;
private static final int NUM_FREE = 3;
private static final double TRANS_FEE = 2.0;
public CheckingAccount(String accNumber, String accName) {
super(accNumber, accName);
transactionCount = 0;
}
public boolean deposit(double amount) {
if (super.deposit(amount)) {
transactionCount++;
return true;
}
return false;
}

20

https://www.facebook.com/Oxus20
CheckingAccount Class (contd.)
public boolean withdraw(double amount) {
if (super.withdraw(amount)) {
transactionCount++;
return true;
}
return false;
}
public void deductFees() {
if (transactionCount > NUM_FREE) {
double fees = TRANS_FEE * (transactionCount - NUM_FREE);
if (super.withdraw(fees)) {
transactionCount = 0;
}
}
}
}
https://www.facebook.com/Oxus20

21
CheckingAccount Demo
public class CheckingAccountDemo {
public static void main(String[] args) {
CheckingAccount checking = new CheckingAccount("20120",
"Abdul Rahman Sherzad");
checking.deposit(500);
checking.withdraw(200);
checking.deposit(700);
// No deduction fee because we had only 3 transactions

checking.deductFees();
System.out.println("transactions <= 3: " + checking.getBalance());
// One more transaction

checking.deposit(200);
// Deduction fee occurs because we have had 4 transactions

checking.deductFees();
System.out.println("transactions > 3: " + checking.getBalance());
}

22

}
https://www.facebook.com/Oxus20
Polymorphism Definition
» Polymorphism is the ability of an object to take
on many forms.

» The most common use of polymorphism in OOP
occurs when a parent class reference is used to
refer to a child class object.
23

https://www.facebook.com/Oxus20
Polymorphism In BankAccount
» A SavingsAccount IS_A BankAccount (with some extra functionality)
» A CheckingAccount IS_A BankAccount (with some extra functionality)

» Whatever you can do to a BankAccount (i.e. deposit, withdraw); you can
do with a SavingsAccount or CheckingAccount
» Derived classes can certainly do more (i.e. addInterest) for
SavingsAccount)
» Derived classes may do things differently (i.e. deposit for
CheckingAccount)
24

https://www.facebook.com/Oxus20
Polymorphism In BankAccount Example
public class BankAccountPolymorphismDemo {
public static void main(String[] args) {
BankAccount firstAccount = new SavingsAccount("20120",
"Abdul Rahman Sherzad", 10);
BankAccount secondAccount = new CheckingAccount("20120",
"Abdul Rahman Sherzad");
// calls the method defined in BankAccount

firstAccount.deposit(100.0);
// calls the method defined in CheckingAccount
// because deposit() is overridden in CheckingAccount

secondAccount.deposit(100.0);
}
}
25

https://www.facebook.com/Oxus20
Instanceof Operator
» if you need to determine the specific type
of an object
˃ use the instanceof operator
˃ can then downcast from the general to the more specific type
˃ For example the object from BankAccount Parent Class will be
casted to either SavingsAccount and/or CheckingAccount

26

https://www.facebook.com/Oxus20
END

27

https://www.facebook.com/Oxus20

More Related Content

What's hot

Presentation web based application|Web designing training center in coimbator...
Presentation web based application|Web designing training center in coimbator...Presentation web based application|Web designing training center in coimbator...
Presentation web based application|Web designing training center in coimbator...Vignesh026
 
Online banking system
Online banking systemOnline banking system
Online banking systemVivek Poddar
 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object ModelWebStackAcademy
 
Java - Generic programming
Java - Generic programmingJava - Generic programming
Java - Generic programmingRiccardo Cardin
 
Durga soft scjp-notes-part-1-javabynataraj
Durga soft scjp-notes-part-1-javabynatarajDurga soft scjp-notes-part-1-javabynataraj
Durga soft scjp-notes-part-1-javabynatarajSatya Johnny
 
JavaScript: Ajax & DOM Manipulation
JavaScript: Ajax & DOM ManipulationJavaScript: Ajax & DOM Manipulation
JavaScript: Ajax & DOM Manipulationborkweb
 
"Bank management system"
"Bank management system""Bank management system"
"Bank management system"vivek kct
 
Introduction to Python programming
Introduction to Python programmingIntroduction to Python programming
Introduction to Python programmingDamian T. Gordon
 
Object Oriented Programming
Object Oriented ProgrammingObject Oriented Programming
Object Oriented ProgrammingIqra khalil
 
Object oriented programming concept
Object oriented programming conceptObject oriented programming concept
Object oriented programming conceptPina Parmar
 
The Singleton Pattern Presentation
The Singleton Pattern PresentationThe Singleton Pattern Presentation
The Singleton Pattern PresentationJAINIK PATEL
 
Looping statements in Java
Looping statements in JavaLooping statements in Java
Looping statements in JavaJin Castor
 

What's hot (20)

Presentation web based application|Web designing training center in coimbator...
Presentation web based application|Web designing training center in coimbator...Presentation web based application|Web designing training center in coimbator...
Presentation web based application|Web designing training center in coimbator...
 
Online banking system
Online banking systemOnline banking system
Online banking system
 
Oops in Java
Oops in JavaOops in Java
Oops in Java
 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object Model
 
JAVA PROGRAMMING
JAVA PROGRAMMING JAVA PROGRAMMING
JAVA PROGRAMMING
 
Java - Generic programming
Java - Generic programmingJava - Generic programming
Java - Generic programming
 
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programming
 
Oop Presentation
Oop PresentationOop Presentation
Oop Presentation
 
Durga soft scjp-notes-part-1-javabynataraj
Durga soft scjp-notes-part-1-javabynatarajDurga soft scjp-notes-part-1-javabynataraj
Durga soft scjp-notes-part-1-javabynataraj
 
JavaScript: Ajax & DOM Manipulation
JavaScript: Ajax & DOM ManipulationJavaScript: Ajax & DOM Manipulation
JavaScript: Ajax & DOM Manipulation
 
"Bank management system"
"Bank management system""Bank management system"
"Bank management system"
 
Wrapper class
Wrapper classWrapper class
Wrapper class
 
Interface in java
Interface in javaInterface in java
Interface in java
 
Introduction to Python programming
Introduction to Python programmingIntroduction to Python programming
Introduction to Python programming
 
Object Oriented Programming
Object Oriented ProgrammingObject Oriented Programming
Object Oriented Programming
 
Object oriented programming concept
Object oriented programming conceptObject oriented programming concept
Object oriented programming concept
 
The Singleton Pattern Presentation
The Singleton Pattern PresentationThe Singleton Pattern Presentation
The Singleton Pattern Presentation
 
Object Oriented Design
Object Oriented DesignObject Oriented Design
Object Oriented Design
 
concept of oops
concept of oopsconcept of oops
concept of oops
 
Looping statements in Java
Looping statements in JavaLooping statements in Java
Looping statements in Java
 

Viewers also liked

Java Arrays
Java ArraysJava Arrays
Java ArraysOXUS 20
 
Java Applet and Graphics
Java Applet and GraphicsJava Applet and Graphics
Java Applet and GraphicsOXUS 20
 
PHP Basic and Fundamental Questions and Answers with Detail Explanation
PHP Basic and Fundamental Questions and Answers with Detail ExplanationPHP Basic and Fundamental Questions and Answers with Detail Explanation
PHP Basic and Fundamental Questions and Answers with Detail ExplanationOXUS 20
 
Java Regular Expression PART I
Java Regular Expression PART IJava Regular Expression PART I
Java Regular Expression PART IOXUS 20
 
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton ClassesJava Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton ClassesOXUS 20
 
Java Regular Expression PART II
Java Regular Expression PART IIJava Regular Expression PART II
Java Regular Expression PART IIOXUS 20
 
TKP Java Notes for Teaching Kids Programming
TKP Java Notes for Teaching Kids ProgrammingTKP Java Notes for Teaching Kids Programming
TKP Java Notes for Teaching Kids ProgrammingLynn Langit
 
Fal-e-Hafez (Omens of Hafez) Cards in Persian using Java
Fal-e-Hafez (Omens of Hafez) Cards in Persian using JavaFal-e-Hafez (Omens of Hafez) Cards in Persian using Java
Fal-e-Hafez (Omens of Hafez) Cards in Persian using JavaOXUS 20
 
Conditional Statement
Conditional Statement Conditional Statement
Conditional Statement OXUS 20
 
Java Unicode with Cool GUI Examples
Java Unicode with Cool GUI ExamplesJava Unicode with Cool GUI Examples
Java Unicode with Cool GUI ExamplesOXUS 20
 
Object Oriented Concept Static vs. Non Static
Object Oriented Concept Static vs. Non StaticObject Oriented Concept Static vs. Non Static
Object Oriented Concept Static vs. Non StaticOXUS 20
 
Java Guessing Game Number Tutorial
Java Guessing Game Number TutorialJava Guessing Game Number Tutorial
Java Guessing Game Number TutorialOXUS 20
 
Structure programming – Java Programming – Theory
Structure programming – Java Programming – TheoryStructure programming – Java Programming – Theory
Structure programming – Java Programming – TheoryOXUS 20
 
Create Splash Screen with Java Step by Step
Create Splash Screen with Java Step by StepCreate Splash Screen with Java Step by Step
Create Splash Screen with Java Step by StepOXUS 20
 
Web Design and Development Life Cycle and Technologies
Web Design and Development Life Cycle and TechnologiesWeb Design and Development Life Cycle and Technologies
Web Design and Development Life Cycle and TechnologiesOXUS 20
 
Note - Java Remote Debug
Note - Java Remote DebugNote - Java Remote Debug
Note - Java Remote Debugboyw165
 
Everything about Database JOINS and Relationships
Everything about Database JOINS and RelationshipsEverything about Database JOINS and Relationships
Everything about Database JOINS and RelationshipsOXUS 20
 
Core java notes with examples
Core java notes with examplesCore java notes with examples
Core java notes with examplesbindur87
 
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton ClassesJava Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton ClassesAbdul Rahman Sherzad
 
Java Unicode with Live GUI Examples
Java Unicode with Live GUI ExamplesJava Unicode with Live GUI Examples
Java Unicode with Live GUI ExamplesAbdul Rahman Sherzad
 

Viewers also liked (20)

Java Arrays
Java ArraysJava Arrays
Java Arrays
 
Java Applet and Graphics
Java Applet and GraphicsJava Applet and Graphics
Java Applet and Graphics
 
PHP Basic and Fundamental Questions and Answers with Detail Explanation
PHP Basic and Fundamental Questions and Answers with Detail ExplanationPHP Basic and Fundamental Questions and Answers with Detail Explanation
PHP Basic and Fundamental Questions and Answers with Detail Explanation
 
Java Regular Expression PART I
Java Regular Expression PART IJava Regular Expression PART I
Java Regular Expression PART I
 
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton ClassesJava Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
 
Java Regular Expression PART II
Java Regular Expression PART IIJava Regular Expression PART II
Java Regular Expression PART II
 
TKP Java Notes for Teaching Kids Programming
TKP Java Notes for Teaching Kids ProgrammingTKP Java Notes for Teaching Kids Programming
TKP Java Notes for Teaching Kids Programming
 
Fal-e-Hafez (Omens of Hafez) Cards in Persian using Java
Fal-e-Hafez (Omens of Hafez) Cards in Persian using JavaFal-e-Hafez (Omens of Hafez) Cards in Persian using Java
Fal-e-Hafez (Omens of Hafez) Cards in Persian using Java
 
Conditional Statement
Conditional Statement Conditional Statement
Conditional Statement
 
Java Unicode with Cool GUI Examples
Java Unicode with Cool GUI ExamplesJava Unicode with Cool GUI Examples
Java Unicode with Cool GUI Examples
 
Object Oriented Concept Static vs. Non Static
Object Oriented Concept Static vs. Non StaticObject Oriented Concept Static vs. Non Static
Object Oriented Concept Static vs. Non Static
 
Java Guessing Game Number Tutorial
Java Guessing Game Number TutorialJava Guessing Game Number Tutorial
Java Guessing Game Number Tutorial
 
Structure programming – Java Programming – Theory
Structure programming – Java Programming – TheoryStructure programming – Java Programming – Theory
Structure programming – Java Programming – Theory
 
Create Splash Screen with Java Step by Step
Create Splash Screen with Java Step by StepCreate Splash Screen with Java Step by Step
Create Splash Screen with Java Step by Step
 
Web Design and Development Life Cycle and Technologies
Web Design and Development Life Cycle and TechnologiesWeb Design and Development Life Cycle and Technologies
Web Design and Development Life Cycle and Technologies
 
Note - Java Remote Debug
Note - Java Remote DebugNote - Java Remote Debug
Note - Java Remote Debug
 
Everything about Database JOINS and Relationships
Everything about Database JOINS and RelationshipsEverything about Database JOINS and Relationships
Everything about Database JOINS and Relationships
 
Core java notes with examples
Core java notes with examplesCore java notes with examples
Core java notes with examples
 
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton ClassesJava Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
 
Java Unicode with Live GUI Examples
Java Unicode with Live GUI ExamplesJava Unicode with Live GUI Examples
Java Unicode with Live GUI Examples
 

Similar to OOP Concepts: Classes, Objects, Encapsulation, Inheritance, Polymorphism

Dependency injection - the right way
Dependency injection - the right wayDependency injection - the right way
Dependency injection - the right wayThibaud Desodt
 
Creating Single Page Web App using Backbone JS
Creating Single Page Web App using Backbone JSCreating Single Page Web App using Backbone JS
Creating Single Page Web App using Backbone JSAkshay Mathur
 
Php & Web Security - PHPXperts 2009
Php & Web Security - PHPXperts 2009Php & Web Security - PHPXperts 2009
Php & Web Security - PHPXperts 2009mirahman
 
Bdd with Cucumber and Mocha
Bdd with Cucumber and MochaBdd with Cucumber and Mocha
Bdd with Cucumber and MochaAtish Narlawar
 
CLOUD DEPLOYMENT ARCHITECTURE 1 Cloud Deploymen
CLOUD DEPLOYMENT ARCHITECTURE      1 Cloud DeploymenCLOUD DEPLOYMENT ARCHITECTURE      1 Cloud Deploymen
CLOUD DEPLOYMENT ARCHITECTURE 1 Cloud DeploymenWilheminaRossi174
 
Mvc4 crud operations.-kemuning senja
Mvc4 crud operations.-kemuning senjaMvc4 crud operations.-kemuning senja
Mvc4 crud operations.-kemuning senjaalifha12
 
Using pandas library for data analysis in python
Using pandas library for data analysis in pythonUsing pandas library for data analysis in python
Using pandas library for data analysis in pythonBruce Jenks
 
Cbsecomputersciencecclass12boardproject bankmanagmentsystem-180703065625-conv...
Cbsecomputersciencecclass12boardproject bankmanagmentsystem-180703065625-conv...Cbsecomputersciencecclass12boardproject bankmanagmentsystem-180703065625-conv...
Cbsecomputersciencecclass12boardproject bankmanagmentsystem-180703065625-conv...sriram sarwan
 
Sabarish_php_resume
Sabarish_php_resumeSabarish_php_resume
Sabarish_php_resumesabarish K
 
Entity frame work by Salman Mushtaq -1-
Entity frame work by Salman Mushtaq -1-Entity frame work by Salman Mushtaq -1-
Entity frame work by Salman Mushtaq -1-Salman Mushtaq
 
Apex Enterprise Patterns: Building Strong Foundations
Apex Enterprise Patterns: Building Strong FoundationsApex Enterprise Patterns: Building Strong Foundations
Apex Enterprise Patterns: Building Strong FoundationsSalesforce Developers
 
A test framework out of the box - Geb for Web and mobile
A test framework out of the box - Geb for Web and mobileA test framework out of the box - Geb for Web and mobile
A test framework out of the box - Geb for Web and mobileGlobalLogic Ukraine
 
CSC139 Chapter 9 Lab Assignments (1) Classes and Obj.docx
CSC139 Chapter 9 Lab Assignments (1) Classes and Obj.docxCSC139 Chapter 9 Lab Assignments (1) Classes and Obj.docx
CSC139 Chapter 9 Lab Assignments (1) Classes and Obj.docxruthannemcmullen
 
JavaScript- Functions and arrays.pptx
JavaScript- Functions and arrays.pptxJavaScript- Functions and arrays.pptx
JavaScript- Functions and arrays.pptxMegha V
 

Similar to OOP Concepts: Classes, Objects, Encapsulation, Inheritance, Polymorphism (20)

Dependency injection - the right way
Dependency injection - the right wayDependency injection - the right way
Dependency injection - the right way
 
Ch03
Ch03Ch03
Ch03
 
Ch03
Ch03Ch03
Ch03
 
Creating Single Page Web App using Backbone JS
Creating Single Page Web App using Backbone JSCreating Single Page Web App using Backbone JS
Creating Single Page Web App using Backbone JS
 
Php & Web Security - PHPXperts 2009
Php & Web Security - PHPXperts 2009Php & Web Security - PHPXperts 2009
Php & Web Security - PHPXperts 2009
 
Bdd with Cucumber and Mocha
Bdd with Cucumber and MochaBdd with Cucumber and Mocha
Bdd with Cucumber and Mocha
 
CAD Report
CAD ReportCAD Report
CAD Report
 
CLOUD DEPLOYMENT ARCHITECTURE 1 Cloud Deploymen
CLOUD DEPLOYMENT ARCHITECTURE      1 Cloud DeploymenCLOUD DEPLOYMENT ARCHITECTURE      1 Cloud Deploymen
CLOUD DEPLOYMENT ARCHITECTURE 1 Cloud Deploymen
 
Mvc4 crud operations.-kemuning senja
Mvc4 crud operations.-kemuning senjaMvc4 crud operations.-kemuning senja
Mvc4 crud operations.-kemuning senja
 
Using pandas library for data analysis in python
Using pandas library for data analysis in pythonUsing pandas library for data analysis in python
Using pandas library for data analysis in python
 
Inheritance
InheritanceInheritance
Inheritance
 
Cbsecomputersciencecclass12boardproject bankmanagmentsystem-180703065625-conv...
Cbsecomputersciencecclass12boardproject bankmanagmentsystem-180703065625-conv...Cbsecomputersciencecclass12boardproject bankmanagmentsystem-180703065625-conv...
Cbsecomputersciencecclass12boardproject bankmanagmentsystem-180703065625-conv...
 
Sabarish_php_resume
Sabarish_php_resumeSabarish_php_resume
Sabarish_php_resume
 
Entity frame work by Salman Mushtaq -1-
Entity frame work by Salman Mushtaq -1-Entity frame work by Salman Mushtaq -1-
Entity frame work by Salman Mushtaq -1-
 
BANK MANAGEMENT SYSTEM report
BANK MANAGEMENT SYSTEM reportBANK MANAGEMENT SYSTEM report
BANK MANAGEMENT SYSTEM report
 
Apex Enterprise Patterns: Building Strong Foundations
Apex Enterprise Patterns: Building Strong FoundationsApex Enterprise Patterns: Building Strong Foundations
Apex Enterprise Patterns: Building Strong Foundations
 
Yii Introduction
Yii IntroductionYii Introduction
Yii Introduction
 
A test framework out of the box - Geb for Web and mobile
A test framework out of the box - Geb for Web and mobileA test framework out of the box - Geb for Web and mobile
A test framework out of the box - Geb for Web and mobile
 
CSC139 Chapter 9 Lab Assignments (1) Classes and Obj.docx
CSC139 Chapter 9 Lab Assignments (1) Classes and Obj.docxCSC139 Chapter 9 Lab Assignments (1) Classes and Obj.docx
CSC139 Chapter 9 Lab Assignments (1) Classes and Obj.docx
 
JavaScript- Functions and arrays.pptx
JavaScript- Functions and arrays.pptxJavaScript- Functions and arrays.pptx
JavaScript- Functions and arrays.pptx
 

More from Abdul Rahman Sherzad

Data is the Fuel of Organizations: Opportunities and Challenges in Afghanistan
Data is the Fuel of Organizations: Opportunities and Challenges in AfghanistanData is the Fuel of Organizations: Opportunities and Challenges in Afghanistan
Data is the Fuel of Organizations: Opportunities and Challenges in AfghanistanAbdul Rahman Sherzad
 
PHP Unicode Input Validation Snippets
PHP Unicode Input Validation SnippetsPHP Unicode Input Validation Snippets
PHP Unicode Input Validation SnippetsAbdul Rahman Sherzad
 
Sorting Alpha Numeric Data in MySQL
Sorting Alpha Numeric Data in MySQLSorting Alpha Numeric Data in MySQL
Sorting Alpha Numeric Data in MySQLAbdul Rahman Sherzad
 
Cross Join Example and Applications
Cross Join Example and ApplicationsCross Join Example and Applications
Cross Join Example and ApplicationsAbdul Rahman Sherzad
 
Applicability of Educational Data Mining in Afghanistan: Opportunities and Ch...
Applicability of Educational Data Mining in Afghanistan: Opportunities and Ch...Applicability of Educational Data Mining in Afghanistan: Opportunities and Ch...
Applicability of Educational Data Mining in Afghanistan: Opportunities and Ch...Abdul Rahman Sherzad
 
Web Application Security and Awareness
Web Application Security and AwarenessWeb Application Security and Awareness
Web Application Security and AwarenessAbdul Rahman Sherzad
 
Database Automation with MySQL Triggers and Event Schedulers
Database Automation with MySQL Triggers and Event SchedulersDatabase Automation with MySQL Triggers and Event Schedulers
Database Automation with MySQL Triggers and Event SchedulersAbdul Rahman Sherzad
 
Evaluation of Existing Web Structure of Afghan Universities
Evaluation of Existing Web Structure of Afghan UniversitiesEvaluation of Existing Web Structure of Afghan Universities
Evaluation of Existing Web Structure of Afghan UniversitiesAbdul Rahman Sherzad
 
PHP Basic and Fundamental Questions and Answers with Detail Explanation
PHP Basic and Fundamental Questions and Answers with Detail ExplanationPHP Basic and Fundamental Questions and Answers with Detail Explanation
PHP Basic and Fundamental Questions and Answers with Detail ExplanationAbdul Rahman Sherzad
 
Fundamentals of Database Systems Questions and Answers
Fundamentals of Database Systems Questions and AnswersFundamentals of Database Systems Questions and Answers
Fundamentals of Database Systems Questions and AnswersAbdul Rahman Sherzad
 
Everything about Database JOINS and Relationships
Everything about Database JOINS and RelationshipsEverything about Database JOINS and Relationships
Everything about Database JOINS and RelationshipsAbdul Rahman Sherzad
 
Create Splash Screen with Java Step by Step
Create Splash Screen with Java Step by StepCreate Splash Screen with Java Step by Step
Create Splash Screen with Java Step by StepAbdul Rahman Sherzad
 
Fal-e-Hafez (Omens of Hafez) Cards in Persian using Java
Fal-e-Hafez (Omens of Hafez) Cards in Persian using JavaFal-e-Hafez (Omens of Hafez) Cards in Persian using Java
Fal-e-Hafez (Omens of Hafez) Cards in Persian using JavaAbdul Rahman Sherzad
 
Web Design and Development Life Cycle and Technologies
Web Design and Development Life Cycle and TechnologiesWeb Design and Development Life Cycle and Technologies
Web Design and Development Life Cycle and TechnologiesAbdul Rahman Sherzad
 

More from Abdul Rahman Sherzad (20)

Data is the Fuel of Organizations: Opportunities and Challenges in Afghanistan
Data is the Fuel of Organizations: Opportunities and Challenges in AfghanistanData is the Fuel of Organizations: Opportunities and Challenges in Afghanistan
Data is the Fuel of Organizations: Opportunities and Challenges in Afghanistan
 
PHP Unicode Input Validation Snippets
PHP Unicode Input Validation SnippetsPHP Unicode Input Validation Snippets
PHP Unicode Input Validation Snippets
 
Iterations and Recursions
Iterations and RecursionsIterations and Recursions
Iterations and Recursions
 
Sorting Alpha Numeric Data in MySQL
Sorting Alpha Numeric Data in MySQLSorting Alpha Numeric Data in MySQL
Sorting Alpha Numeric Data in MySQL
 
PHP Variable variables Examples
PHP Variable variables ExamplesPHP Variable variables Examples
PHP Variable variables Examples
 
Cross Join Example and Applications
Cross Join Example and ApplicationsCross Join Example and Applications
Cross Join Example and Applications
 
Applicability of Educational Data Mining in Afghanistan: Opportunities and Ch...
Applicability of Educational Data Mining in Afghanistan: Opportunities and Ch...Applicability of Educational Data Mining in Afghanistan: Opportunities and Ch...
Applicability of Educational Data Mining in Afghanistan: Opportunities and Ch...
 
Web Application Security and Awareness
Web Application Security and AwarenessWeb Application Security and Awareness
Web Application Security and Awareness
 
Database Automation with MySQL Triggers and Event Schedulers
Database Automation with MySQL Triggers and Event SchedulersDatabase Automation with MySQL Triggers and Event Schedulers
Database Automation with MySQL Triggers and Event Schedulers
 
Mobile Score Notification System
Mobile Score Notification SystemMobile Score Notification System
Mobile Score Notification System
 
Herat Innovation Lab 2015
Herat Innovation Lab 2015Herat Innovation Lab 2015
Herat Innovation Lab 2015
 
Evaluation of Existing Web Structure of Afghan Universities
Evaluation of Existing Web Structure of Afghan UniversitiesEvaluation of Existing Web Structure of Afghan Universities
Evaluation of Existing Web Structure of Afghan Universities
 
PHP Basic and Fundamental Questions and Answers with Detail Explanation
PHP Basic and Fundamental Questions and Answers with Detail ExplanationPHP Basic and Fundamental Questions and Answers with Detail Explanation
PHP Basic and Fundamental Questions and Answers with Detail Explanation
 
Java Applet and Graphics
Java Applet and GraphicsJava Applet and Graphics
Java Applet and Graphics
 
Fundamentals of Database Systems Questions and Answers
Fundamentals of Database Systems Questions and AnswersFundamentals of Database Systems Questions and Answers
Fundamentals of Database Systems Questions and Answers
 
Everything about Database JOINS and Relationships
Everything about Database JOINS and RelationshipsEverything about Database JOINS and Relationships
Everything about Database JOINS and Relationships
 
Create Splash Screen with Java Step by Step
Create Splash Screen with Java Step by StepCreate Splash Screen with Java Step by Step
Create Splash Screen with Java Step by Step
 
Fal-e-Hafez (Omens of Hafez) Cards in Persian using Java
Fal-e-Hafez (Omens of Hafez) Cards in Persian using JavaFal-e-Hafez (Omens of Hafez) Cards in Persian using Java
Fal-e-Hafez (Omens of Hafez) Cards in Persian using Java
 
Web Design and Development Life Cycle and Technologies
Web Design and Development Life Cycle and TechnologiesWeb Design and Development Life Cycle and Technologies
Web Design and Development Life Cycle and Technologies
 
Java Regular Expression PART II
Java Regular Expression PART IIJava Regular Expression PART II
Java Regular Expression PART II
 

Recently uploaded

Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docxPoojaSen20
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfakmcokerachita
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 

Recently uploaded (20)

Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docx
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdf
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 

OOP Concepts: Classes, Objects, Encapsulation, Inheritance, Polymorphism

  • 2. Agenda » Object Oriented Programming » Definition and Demo ˃ Class ˃ Object ˃ Encapsulation (Information Hiding) ˃ Inheritance ˃ Polymorphism ˃ The instanceof Operator 2 https://www.facebook.com/Oxus20
  • 3. Object Oriented Programming (OOP) » OOP makes it easier for programmers to structure and form software programs. » For the reason that individual objects can be modified without touching other aspects of the program. ˃ It is also easier to update and modify programs written in object-oriented languages. » As software programs have grown larger over the years, OOP has made developing these large programs more manageable. 3 https://www.facebook.com/Oxus20
  • 4. Class Definition » A class is kind of a blueprint or template that refer to the methods and attributes that will be in each object. » BankAccount is a blueprint as follow ˃ State / Attributes + Name + Account number + Type of account + Balance ˃ Behaviors / Methods + To assign initial value + To deposit an account + To withdraw an account + To display name, account number & balance. Now you, me and others can have bank accounts (objects / instances) under the above BankAccount blueprint where each can have different account name, number and balance as well as I can deposit 500USD, you can deposit 300USD, as well as withdraw, etc. https://www.facebook.com/Oxus20 4
  • 5. BankAccount Class Example public class BankAccount { // BankAccount attributes private String accountNumber; private String accountName; private double balance; // BankAccount methods // the constructor public BankAccount(String accNumber, String accName) { accountNumber = accNumber; accountName = accName; balance = 0; } 5 https://www.facebook.com/Oxus20
  • 6. BankAccount Class Example (contd.) // methods to read the attributes public String getAccountName() { return accountName; } public String getAccountNumber() { return accountNumber; } public double getBalance() { return balance; } 6 https://www.facebook.com/Oxus20
  • 7. BankAccount Class Example (contd.) // methods to deposit and withdraw money public boolean deposit(double amount) { if (amount > 0) { balance = balance + amount; return true; } else { return false; } } public boolean withdraw(double amount) { if (amount > balance) { return false; } else { balance = balance - amount; return true; } } 7 } https://www.facebook.com/Oxus20
  • 8. Object Definition » An object holds both variables and methods; one object might represent you, a second object might represent me. » Consider the class of Man and Woman ˃ Me and You are objects » An Object is a particular instance of a given class. When you open a bank account; an object or instance of the class BankAccount will be created for you. https://www.facebook.com/Oxus20 8
  • 9. BankAccount Object Example BankAccount absherzad = new BankAccount("20120", "Abdul Rahman Sherzad"); » absherzad is an object of BankAccount with Account Number of "20120" and Account Name of "Abdul Rahman Sherzad". » absherzad object can deposit, withdraw as well as check the balance. 9 https://www.facebook.com/Oxus20
  • 10. BankAccount Demo public class BankAccountDemo { public static void main(String[] args) { BankAccount absherzad = new BankAccount("20120", "Abdul Rahman Sherzad"); absherzad.deposit(500); absherzad.deposit(1500); System.out.println("Balance is: " + absherzad.getBalance()); //2000 absherzad.withdraw(400); System.out.println("Balance is: " + absherzad.getBalance()); //1600 } } 10 https://www.facebook.com/Oxus20
  • 11. Encapsulation Definition » Encapsulation is the technique of making the class attributes private and providing access to the attributes via public methods. » If attributes are declared private, it cannot be accessed by anyone outside the class. ˃ For this reason, encapsulation is also referred to as Data Hiding (Information Hiding). » Encapsulation can be described as a protective barrier that prevents the code and data corruption. » The main benefit of encapsulation is the ability to modify our implemented code without breaking the code of others who use our code. https://www.facebook.com/Oxus20 11
  • 12. Encapsulation Benefit Demo public class EncapsulationDemo { public static void main(String[] args) { BankAccount absherzad = new BankAccount("20120", absherzad.deposit(500); "Abdul Rahman Sherzad"); // Not possible because withdraw() check the withdraw amount with balance // Because current balance is 500 and less than withdraw amount is 1000 absherzad.withdraw(1000); // Encapsulation Benefit // Not possible because class balance is private // and not accessible directly outside the BankAccount class absherzad.balance = 120000; // Encapsulation Benefit } } 12 https://www.facebook.com/Oxus20
  • 13. Inheritance Definition » inheritance is a mechanism for enhancing existing classes ˃ Inheritance is one of the other most powerful techniques of object-oriented programming ˃ Inheritance allows for large-scale code reuse » with inheritance, you can derive a new class from an existing one ˃ automatically inherit all of the attributes and methods of the existing class ˃ only need to add attributes and / or methods for new functionality 13 https://www.facebook.com/Oxus20
  • 14. BankAccount Inheritance Example » Savings Account is a bank account with interest » Checking Account is a bank account with transaction fees 14 https://www.facebook.com/Oxus20
  • 15. Specialty Bank Accounts » now we want to implement SavingsAccount and CheckingAccount ˃ A SavingsAccount is a bank account with an associated interest rate, interest is calculated and added to the balance periodically ˃ could copy-and-paste the code for BankAccount, then add an attribute for interest rate and a method for adding interest ˃ A CheckingAccount is a bank account with some number of free transactions, with a fee charged for subsequent transactions ˃ could copy-and-paste the code for BankAccount, then add an attribute to keep track of the number of transactions and a method for deducting fees 15 https://www.facebook.com/Oxus20
  • 16. Disadvantages of the copy-and-paste Approach » tedious and boring work » lots of duplicate and redundant code ˃ if you change the code in one place, you have to change it everywhere or else lose consistency (e.g., add customer name to the bank account info) » limits polymorphism (will explain later) 16 https://www.facebook.com/Oxus20
  • 17. SavingsAccount class (inheritance provides a better solution) » SavingsAccount can be defined to be a special kind of BankAccount » Automatically inherit common features (balance, account #, account name, deposit, withdraw) » Simply add the new features specific to a SavingsAccount » Need to store interest rate, provide method for adding interest to the balance » General form for inheritance: public class DERIVED_CLASS extends EXISTING_CLASS { ADDITIONAL_ATTRIBUTES ADDITIONAL_METHODS } 17 https://www.facebook.com/Oxus20
  • 18. SavingsAccount Class public class SavingsAccount extends BankAccount { private double interestRate; public SavingsAccount(String accNumber, String accName, double rate) { super(accNumber, accName); interestRate = rate; } public void addInterest() { double interest = getBalance() * interestRate / 100; this.deposit(interest); } } 18 https://www.facebook.com/Oxus20
  • 19. SavingsAccount Demo public class SavingsAccountDemo { public static void main(String[] args) { SavingsAccount saving = new SavingsAccount("20120", "Abdul Rahman Sherzad", 10); // deposit() is inherited from BankAccount (PARENT CLASS) saving.deposit(500); // getBalance() is also inherited from BankAccount (PARENT CLASS) System.out.println("Before Interest: " + saving.getBalance()); saving.addInterest(); System.out.println("After Interest: " + saving.getBalance()); } } 19 https://www.facebook.com/Oxus20
  • 20. CheckingAccount Class public class CheckingAccount extends BankAccount { private int transactionCount; private static final int NUM_FREE = 3; private static final double TRANS_FEE = 2.0; public CheckingAccount(String accNumber, String accName) { super(accNumber, accName); transactionCount = 0; } public boolean deposit(double amount) { if (super.deposit(amount)) { transactionCount++; return true; } return false; } 20 https://www.facebook.com/Oxus20
  • 21. CheckingAccount Class (contd.) public boolean withdraw(double amount) { if (super.withdraw(amount)) { transactionCount++; return true; } return false; } public void deductFees() { if (transactionCount > NUM_FREE) { double fees = TRANS_FEE * (transactionCount - NUM_FREE); if (super.withdraw(fees)) { transactionCount = 0; } } } } https://www.facebook.com/Oxus20 21
  • 22. CheckingAccount Demo public class CheckingAccountDemo { public static void main(String[] args) { CheckingAccount checking = new CheckingAccount("20120", "Abdul Rahman Sherzad"); checking.deposit(500); checking.withdraw(200); checking.deposit(700); // No deduction fee because we had only 3 transactions checking.deductFees(); System.out.println("transactions <= 3: " + checking.getBalance()); // One more transaction checking.deposit(200); // Deduction fee occurs because we have had 4 transactions checking.deductFees(); System.out.println("transactions > 3: " + checking.getBalance()); } 22 } https://www.facebook.com/Oxus20
  • 23. Polymorphism Definition » Polymorphism is the ability of an object to take on many forms. » The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object. 23 https://www.facebook.com/Oxus20
  • 24. Polymorphism In BankAccount » A SavingsAccount IS_A BankAccount (with some extra functionality) » A CheckingAccount IS_A BankAccount (with some extra functionality) » Whatever you can do to a BankAccount (i.e. deposit, withdraw); you can do with a SavingsAccount or CheckingAccount » Derived classes can certainly do more (i.e. addInterest) for SavingsAccount) » Derived classes may do things differently (i.e. deposit for CheckingAccount) 24 https://www.facebook.com/Oxus20
  • 25. Polymorphism In BankAccount Example public class BankAccountPolymorphismDemo { public static void main(String[] args) { BankAccount firstAccount = new SavingsAccount("20120", "Abdul Rahman Sherzad", 10); BankAccount secondAccount = new CheckingAccount("20120", "Abdul Rahman Sherzad"); // calls the method defined in BankAccount firstAccount.deposit(100.0); // calls the method defined in CheckingAccount // because deposit() is overridden in CheckingAccount secondAccount.deposit(100.0); } } 25 https://www.facebook.com/Oxus20
  • 26. Instanceof Operator » if you need to determine the specific type of an object ˃ use the instanceof operator ˃ can then downcast from the general to the more specific type ˃ For example the object from BankAccount Parent Class will be casted to either SavingsAccount and/or CheckingAccount 26 https://www.facebook.com/Oxus20