OOP IN DETAIL
Classes and Objects
In object oriented programming, classes can be likened to blueprints
e.g. the engineering drawing for a vehicle, while objects can be
compared to the actual vehicles built from the blueprints.
Just as the engineering drawing contains all the design details for the
parts of the vehicle, a class contains the definition of the attributes
(data) and behavior (method) of the class. However only instances of
the class i.e. objects of the class can animate the class behavior.
Consider this example
//[Link]
//Account class with a constructor to validate and initialize
//instance variable balance for type double
public class Account
{
private double balance; //instance variable that stores the balance
//constructor
public Account(double initialBalance)
{
//validate that initialBalance is greater than 0.0
//if it is not, balance is initialized to the default value 0.0
if (initialBalance > 0.0)
{
balance = initialBalance;
}
}
//credit(add) an amount to the account
public void credit(double amount)
{
balance = balance + amount; //add amount to balance
}//end method credit
//return the account balance
public double getBalance()
{
return balance; //gives the value of balance to the calling method
}//end method getBalance
}//end class Account
Next, we create instances of the class Account, Account1 and Account2 in the class [Link].
//[Link]
//Inputting and outputting floating-point numbers with Account objects.
import [Link];
public class AccountTest
{
public static void main(String[] args)
{
Account Account1 = new Account (50.00); //create Account object Account1
Account Account2 = new Account (-7.53); //create Account object Account2
//display initial balance of each object
[Link]("Account1 balance: N%.2f\n", [Link]());
[Link]("Account2 balance: N%.2f\n\n", [Link]());
//create Scanner to obtain input from command window
Scanner input = new Scanner ([Link]);
double depositAmount = [Link](); //obtain user input
[Link]("\n adding N%.2f to Account2 balance\n\n", depositAmount);
[Link](depositAmount); //add to Account2 balance
//display balance
[Link]("Account1 balance: N%.2f\n", [Link]());
[Link]("Account2 balance: N%.2f\n", [Link]());
}
}
Encapsulation
This concept is also known as hiding. Data is encapsulated in order to
prevent random access and manipulation by code outside the class
within which data is defined. This can be achieved by declaring the
fields (data) in a class as private and providing access to the fields via
public methods
Inheritance
Inheritance, in OOP is designed to allow a new class to absorb or inherit an
existing class’s members and improve them with new or modified
capabilities. This feature can save time during program development by
basing new classes on existing, testing, proven and high-quality software.
The existing class is called the superclass (base class) and the new class is
the subclass (derived class). A subclass can become a superclass to future
subclasses, this forms a class hierarchy. Is-a relationship represents
inheritance.
Inheritance Hierarchy
Shapes
TwoDimensionalShape ThreeDimensionalShape
Circle Square Triangle Sphere Cube Tetrahedron
Example – Parent class //method to set address
//[Link] public void setAddress(String address1)
{
//creating abstract class Account contains the essential elements address = address1;
//of the concrete classes Current and Savings Accounts }
public abstract class Account
{
private String firstName; //variable to store the first name of the owner of the account //method to return address
public String getAddress()
private String lastName; //variable to store the last name of the owner of the account {
private String address; //variable to store the address of the owner of the account return address;
private int accNo; //variable to store the account number of the owner of the account }
private double accBalance; //variable to store the account balance of the owner of the account
//method to set account number
public void setAccNo(int accNo1)
//constructor to initialize the variables and create account {
public Account(String first, String last, String address1, int accNo1, double accBalance1) accNo = accNo1;
{ }
firstName = first;
lastName = last;
//method to return account number
address = address1; public String getAccNo()
accNo = accNo1; {
accBalance = accBalance1; return accNo;
} }
//method to set Account balance
//method to set the first name public void setAccBalance(doubleaccBalance1)
public void setFirstName(String first) {
{ accBalance = accBalance1;
firstName = first; }
}
//method to return Account balance
//method to return first name public String getAccBalance()
public String getFirstName() {
{ return accBalance;
return firstName; }
}
//method to make deposit
public void deposit(double amount)
//method to set last name {
public void setLastName(String last) double balance;
{ balance = getAccBalance(); //call to obtain the balance before deposit
lastName = last; balance += amount; //adds deposit amount to old balance
setAccBalance(balance); //sets the account balance to include deposit
} [Link]("\n\ndeposit successful, %s %s your new balance is %.2f NAIRA ",
getFirstName(), getLastName(), balance); //display the new balance
}
//method to return last name
public String getLastName() public String displayBalance()
{
{ return [Link]("%s %s your account balance is %.2f NAIRA", getFirstName(),
return lastName; getLastName(), getAccBalance());
} }
public abstract void withdrawal(double amount);
}
//[Link]
//creating the concrete class, current account, which is a subclass of Account
public class CurrentAccount extends Account
{
Example – Child Class
private String accType; //additional variable to store account type
//constructor to initialize variables
public CurrentAccount(String first, String last, String address1, int accNo1, double accBalance1, String accType1)
{
//explicit call to super class constructor
super (first, last, address1, accNo1, accBalance1);
accType = accType1;
setAccType (accType1);
}
//method to confirm account creation
public void setAccType(String accType1)
{
if (accType == "Current" || accType == "Corporate")
{
accType = accType1;
[Link] ("\n%s account created for %s %s of %s\n", accType1, getFirstName(), getLastName(), getAddress());
}
else
[Link] ("You typed an incorrect account type");
}
//method to perform overdraft
public void overDraft(double amount)
{
double balance = getAccBalance();
double newBalance = balance –amount - 5; //calculate new balance deducting, withdrawn amount and 5 Naira charge
setAccBalance (newBalance);
}
@override
//method to effect cash withdrawal and override abstract method withdrawal in super class
public void withdrawal(double amount)
{
double availableBalance;
availableBalance = getAccBalance();
if ((availableBalance – amount) < 0)
{
overdraft (amount);
[Link] ("\n\n%s %s you have withdraw more than your available balance and you will be charged 5.00 NAIRA per day for overdraft services. \
nHere’s your cash. Your new balance is %.2f NAIRA", getFirstName(), getLastName(), getAccBalance());
}
else
{
setAccBalance((availableBalance – amount));
[Link] ("\nHere’s your cash. Your new balance is %.2f NAIRA", getAccBalance());
}
}
//[Link]
//creating the concrete class, Savings account, which is a subclass of Account
public class SavingsAccount extends Account
{ Example – Child Class
private String accType; //additional variable to store account type
//constructor to initialize variables
public SavingsAccount(String first, String last, String address1, int accNo1, double accBalance1, String accType1)
{
//explicit call to super class constructor
super (first, last, address1, accNo1, accBalance1);
accType = accType1;
setAccType (accType1);
}
//method to confirm account creation
public void setAccType(String accType1)
{
if (accType == "Savings")
{
accType = accType1;
[Link] ("Savings account created for %s %s of %s\n", getFirstName(), getLastName(), getAddress());
}
else
[Link] ("You typed an incorrect account type");
}
//method to effect cash withdrawal and override abstract method withdrawal in super class
@override
public void withdrawal(double amount)
{
double availableBalance;
availableBalance = getAccBalance(); //obtains the current account balance
if ((availableBalance – amount) < 0) //prevents withdrawal beyond available balance
{
[Link] ("%s %s you cannot withdraw more than your available balance", getFirstName(), getLastName());
}
else
{
availableBalance -= amount;
setAccBalance(availableBalance);
[Link] ("\nHere’s your cash. %s %s your new balance is %.2f NAIRA", getFirstName(), getLastName(),getAccBalance());
}
}
//method to calculate interest
public void computeInterest(double time) //takes time as double, to accept fractions of a year
{
double Interest;
double balance = getAccBalance();
double newBalance;
Interest = 0.05 * time * balance; // calculates interest at 5% interest rate
newBalance = balance + Interest; //adds Interest to old balance to obtain new balance
setAccBalance (newBalance); //sets balance to new balance
[Link] ("\nInterest computed at 5% interest, your new balance is:");
[Link] ("%.2f NAIRA", newBalance);
}
Object Creation
//[Link]
//class to instantiate objects.
public class AccountsTest
{
public static void main(String[] args)
{
//instantiating objects of class SavingsAccount and CurrentAccount
SavingsAccount savingsAccount1 = new SavingsAccount ("Yinka", "Balogun", "Tyndale Street", 33333, 500.00, "Savings");
CurrentAccount currentAccount1 = new CurrentAccount ("Chika", "Nwafor", "Queens Street", 44444, 20.00, "Current");
[Link](200); //testing withdrawal method
[Link](100); //testing deposit method
[Link](3); //testing Interest method
[Link](50); //testing withdrawal method
[Link](); //testing display balance method
[Link](400); //testing deposit method
}
}
The output of the code is:
Savings account created for Yinka Balogun of Tyndale Street
Current account created for Chika Nwafor of Queens Street
Here’s your cash. Yinka Balogun your new balance is 300.00 NAIRA
deposit successful, Yinka Balogun your new balance is 400 NAIRA
interest computed at 5% interest, your new balance is:
460.00 NAIRA
Chika Nwafor you have withdrawn more than your available balance and you will be
charged 5.00 NAIRA per day for overdraft services.
Here is your cash. Your new balance is -35.00 NAIRA
deposit successful, Chika Nwafor your new balance is -365.00 NAIRA
Polymorphism
Polymorphism is the ability of an object to take on many forms. The most common use in
OOP occurs when a parent class reference is used to refer to a child class object. It is
important to know that the only possible way to access an object is through a reference
variable.
This means that an object of a subclass can be treated as an object of its superclass
because each subclass object is-a superclass object. We will create a subclass
CorporateCurrentAccount of the subclass CurrentAccount, which overrides the
method withdrawal. Next we create a reference of type CurrentAccount, and we
assign an object of type CorporateCurrentAccount to it. When the method
withdrawal is called on the CorporateCurrentAccount the java compiler
polymorphically calls the method of the subclass CorporateCurrentAccount at
runtime.
//[Link]
//creating the concrete class, CorporateCurrent account, which is a subclass of CurrentAccount Example – polymorphism
public class CorporateCurrentAccount extends CurrentAccount
{
//constructor to initialize variables
public CorporateCurrentAccount(String first, String last, String address1, int accNo1, double accBalance1, String accType1)
{
//explicit call to super class constructor
super (first, last, address1, accNo1, accBalance1, accType1);
}
//method to perform overdraft for Corporate current account
@override
public void overDraft(double amount)
{
double balance = getAccBalance();
double newBalance = balance – amount - 1000; //calculate new balance deducting, withdrawn amount and 1000 Naira charge
setAccBalance (newBalance);
}
@override
//method to effect cash withdrawal and override abstract method withdrawal in super class
public void withdrawal(double amount)
{
double availableBalance;
availableBalance = getAccBalance();
if ((availableBalance – amount) < 0)
{
overdraft (amount);
[Link] ("\n\n%s %s you have withdraw more than your available balance and you will be charged 1000.00 NAIRA per
day for overdraft services. \nHere is your cash. Your new balance is %.2f NAIRA", getFirstName(), getLastName(),
getAccBalance());
}
else
{
setAccBalance((availableBalance – amount));
[Link] ("\nHere’s your cash. Your new balance is %.2f NAIRA", getAccBalance());
}
}
}
Creating Objects – to
//[Link]
//class to instantiate objects.
demonstrate polymorphism
public class TestPoly
{
public static void main(String[] args)
{
//creating reference of type CurrentAccount and aim at CorporateCurrentAccount object
CurrentAccount CorpCurrentAccount = new CorporateCurrentAccount ("Yemi", "Akin", "London Street", 55555, 2000.00,
"Corporate");
[Link](5000);
[Link]();
}
}
The output of the code is:
Corporate account created for Yemi Akin of London Street
Yemi Akin you have withdrawn more than your available balance and you will be charged 1000.00 NAIRA per day for overdraft
services.
Here is your cash. Your new balance is -4000.00 NAIRA