Lab 07 Java - 2k21
Lab 07 Java - 2k21
Lab Manual - 7
OOP
3rdSemester Lab-07: Constructor and Method Overloading
Laboratory 07:
Statement Purpose:
At the end of this lab, the students should be able to:
Constructor:
A constructor initializes an object immediately upon creation. It has the same name as the
class in which it resides and has no return type, not even void.
System.out.println(circle1.area( ));
System.out.println(circle2.area( ));
System.out.println(circle1.perimeter( ));
System.out.println(circle2.perimeter( ));
circle1.changeTheRadius(5);
circle1.output( );
circle2.output( );
circle1.changeTheRadius(6);
circle1.output( );
circle2.output( );
circle3=new MyCircle(circle1);
circle3.output();
System.out.println("circle 3:"+circle3.area( ));
System.out.println("circle 3:"+circle3.perimeter( ));
} }
Output:
When you begin to create your own classes, providing many forms of constructor is usually
required to allow objects to be constructed in a convenient and efficient manner.
Note: A static constructor is not allowed in Java programming. It is illegal and against the Java
standards to use a static constructor. So, the Java program will not be compiled and throw a
compile-time error.
Method Overloading:
• In Java, it is possible to define two or more methods within the same class that share the
same name, as long as their parameter declarations are different. These methods are said
to be overloaded.
• When an overloaded method is called, Java uses the type and/or number of arguments to
determine which version of the overloaded method to call. Thus, overloaded methods must
differ in the type and/or number of their parameters. They may have different return types,
since return types do not play a role in overload resolution. The sequence of arguments
must also be same just like parameters.
Note: The value of overloading is that it allows related methods to be accessed by use of a common
name.
Example 1:
public class c3 {
void sum(int a,int b)
{
System.out.println(a+b);
}
void sum(int a,int b,int c)
{
System.out.println(a+b+c);
}
public static void main(String args[])
{
c3 obj=new c3();
obj.sum(10,10,10);
obj.sum(20,20);
}
}
Output:
30
40
Example 2:
public class c5 {
int addition(int i, int j)
{
return i + j ;
}
String addition(String s1, String s2)
{
return s1 + s2;
}
double addition(double d1, double d2)
{
return d1 + d2;
}
}
class AddOperation2 {
public static void main(String args[])
{
c5 sObj = new c5();
System.out.println(sObj.addition(1,2));
System.out.println(sObj.addition("Hello ","World"));
System.out.println(sObj.addition(1.5,2));
}
}
Output:
3
Hello World
3.5
Note: Overloaded methods can perform different functions but in practice, you should only overload
closely related operations.
Argument Passing:
There are two ways that a computer language can pass an argument to a method.
Pass-by-value: This method copies the value of an argument into the formal parameter of the method.
Therefore, changes made to the parameter of the method have no effect on the argument.
Pass-by-reference: In this method, a reference to an argument (not the value of the argument) is passed
to the parameter. Inside the method, this reference is used to access the actual argument specified in the
call. This means that changes made to the parameter will affect the argument used to call the method.
Passing By Values
Output:
Passing By Reference:
//PassbyReference Example
public class RecordDemo {
public static void main(String[] args) {
Record id = new Record();
id.num = 2;
id.name = "Basit";
System.out.println("Before method call: "+"name ->"+id.name + " " +"id
->"+ id.num);
tryObject(id);
System.out.println("After method call: "+"name ->"+id.name + " " +"id
->"+ id.num);
}
//Now we can pass the object as a parameter to a method:
public static void tryObject(Record r)
{
r.num = 100;
r.name = "Fareeha";
}
}
class Record
{
int num;
String name;
}
Output:
Note that the object's instances variables are changed in this case. The reference to id is the
argument to the method, so the method cannot be used to change that reference, i.e., it can't
make id reference a different Record. But the method can use the reference to perform any
Note: It is often not good programming style to change the values of instance variables outside
the object. Normally, the object would have a method to set the values of its instance variables.
Example:
public class RecordDemo {
}
}
class Record
{
int num;
String name;
Output:
Static Members:
Normally a class member can be accessed using an object of a class. However, it is possible to
create a member that can be used by itself, without reference to a specific instance. To create
such a member, precede its declaration with the keyword static. When a member is declared
static, it can be accessed before any objects of its class are created, and without reference to
any object. Both methods and variables can be declared as static.
//Demonstrate static
public class c7 {
static int a=42;
static int b=99;
static void meth(){
System.out.println("a = " +a);
}
}
class staticByName{
public static void main(String args[])
{
c7.meth();
System.out.println("b = " +c7.b);
}
}
Output:
a = 42
b = 99
Account Class:
File Account.java contains a definition for a simple bank account class with methods to
withdraw, deposit, get the balance and account number, and return a String representation.
Note that the constructor for this class creates a random account number. Save this class to
your directory and study it to see how it works. Then modify it as follows:
• public Account (double initBal, String owner, long number) – initializes the balance, owner,
and account number as specified
• public Account (double initBal, String owner) – initializes the balance and owner as specified;
randomly generates the account number.
• public Account (String owner) – initializes the owner as specified; sets the initial balance to
0 and randomly generates the account number.
Using Random class: To use the Random Class to generate random numbers, follow the
steps below:
2. Overload the withdraw method with one that also takes a fee and deducts that fee from the
account.
3. Perform validity check on the deposit, do not allow the deposit of a negative number.
Print appropriate error message if this occurs.
File TestAccount.java contains a simple program that exercises these methods. Save it to your
directory, study it to see what it does, and use it to test your modified Account class.
Account. Java
//*******************************************************
// Account.java
//
// A bank account class with methods to deposit to, withdraw
from,
// change the name on, and get a String representation
// of the account.
//*******************************************************
//----------------------------------------------
//Constructor -- initializes balance, owner, and account
number
//----------------------------------------------
public Account(double initBal, String owner, long number)
{
balance = initBal;
name = owner;
acctNum = number;
}
//----------------------------------------------
// Checks to see if balance is sufficient for withdrawal.
Engr. Sidra Shafi Lab-07 8
3rdSemester Lab-07: Constructor and Method Overloading
//----------------------------------------------
// Adds deposit amount to balance.
//----------------------------------------------
public void deposit(double amount)
{
balance += amount;
}
//----------------------------------------------
// Returns balance.
//----------------------------------------------
public double getBalance()
{
return balance;
}
//----------------------------------------------
// Returns a string containing the name, account number,
and balance.
//----------------------------------------------
public String toString()
{
return "Name:" + name +
"\nAccount Number: " + acctNum +
"\nBalance: " + balance;
}
}
Test Account.java
//*******************************************************
// TestAccount.java
//
// A simple driver to test the overloaded methods of
// the Account class.
//*******************************************************
import java.util.Scanner;
{
String name;
double balance;
long acctNum;
Account acct;
System.out.println("\nBye!");
}
}
1. Suppose the bank wants to keep track of how many accounts exist.
a. Declare a private static integer variable numAccounts to hold this value. Like all instance
and static variables, it will be initialized (to 0, since it’s an int) automatically.
Engr. Sidra Shafi Lab-07 10
3rdSemester Lab-07: Constructor and Method Overloading
b. Add code to the constructor to increment this variable every time an account is created.
c. Add a static method getNumAccounts that returns the total number of accounts. Think about
why this method should be static – its information is not related to any particular account.
d. File TestAccounts1.java contains a simple program that creates the specified number of bank
accounts then uses the getNumAccounts method to find how many accounts were created.
Save it to your directory, then use it to test your modified Account class.
2. Add a method void close() to your Account class. This method should close the current
account by appending “CLOSED” to the account name and setting the balance to 0. (The
account number should remain unchanged.) Also decrement the total number of accounts.
3. Add a static method Account consolidate(Account acct1, Account acct2) to your Account
class that creates a new account whose balance is the sum of the balances in acct1 and acct2
and closes acct1 and acct2. The new account should be returned. Two important rules of
consolidation:
• Only accounts with the same name can be consolidated. The new account gets the name on
the old accounts but a new account number.
• Two accounts with the same number cannot be consolidated. Otherwise this would be an
easy way to double your money!
Check these conditions before creating the new account. If either condition fails, do not create
the new account or close the old ones; print a useful message and return null.
4. Write a test program that prompts for and reads in three names and creates an account with
an initial balance of $100 for each. Print the three accounts, then close the first account and
try to consolidate the second and third into a new account. Now print the accounts again,
including the consolidated one if it was created.
// TestAccounts1
// A simple program to test the numAccts method of the
// Account class.
import java.util.Scanner;
You can use this code to create three accounts with initial balance of 100.
You can use the sample code shown below to create arraylist of Account type to store
different objects with initial balance of 100 each.
Sample Output:
How many accounts would you like to create?
3
Account Names: Sidra
Account Names: Sidra
Account Names: Ahmed
No. of Accounts created:3
Account 3 is Name:Ahmed
Account Number: 738
Balance: 100.0
New account is Name:Sidra
Account Number: 443
Balance: 200.0
No. of Accounts created:1
account 1 is Name:SidraClosed
Account Number: 442
Balance: 0.0
account 2 is Name:SidraClosed
Account Number: 134
Balance: 0.0
account 3 is Name:AhmedClosed
Account Number: 738
Balance: 0.0
New account is Name:Sidra
Account Number: 443
Balance: 200.0
**********