0% found this document useful (0 votes)
70 views

Lab 07 Java - 2k21

1. The document discusses constructors and method overloading in Java. It provides examples of using different constructors to initialize objects and overloaded methods that differ in parameters. 2. It explains the concepts of pass-by-value and pass-by-reference when passing arguments to methods. Pass-by-value copies the value while pass-by-reference passes a reference. 3. Examples are given to demonstrate that changes to parameters only affect the calling method in pass-by-value, while pass-by-reference allows changing the original arguments.

Uploaded by

Ubair Mirza
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
70 views

Lab 07 Java - 2k21

1. The document discusses constructors and method overloading in Java. It provides examples of using different constructors to initialize objects and overloaded methods that differ in parameters. 2. It explains the concepts of pass-by-value and pass-by-reference when passing arguments to methods. Pass-by-value copies the value while pass-by-reference passes a reference. 3. Examples are given to demonstrate that changes to parameters only affect the calling method in pass-by-value, while pass-by-reference allows changing the original arguments.

Uploaded by

Ubair Mirza
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

UET TAXILA

CLO Learning Outcomes Assessment Item BT Level PLO


No.

1 Construct the experiments / Lab Task, Mid Exam, Final


projects of varying complexities. Exam, Quiz, Assignment, P2 3
Semester Project
2 Use modern tool and languages. Lab Task, Semester
P2 5
Project
3 Demonstrate an original solution of Lab Task, Semester
A2 8
problem under discussion. Project
4 Work individually as well as in Lab Task, Semester A2 9
teams Project

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:

• Implement Constructor and Method Overloading


• Implement Argument Passing (Pass by value and Pass by reference)
• Returning Objects from methods
• Static Members

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.

Using Constructor to initialize an object:

//How to use constructor


class MyCircle
{
private int xcenter;
private int ycenter;
private int radius;
public MyCircle( ) // default constructor (initializer)
{
xcenter = 0;
ycenter = 0;
radius = 1;
}
public MyCircle(int x, int y, int r)//constructor when all parameters are
specified (initializer)
{
xcenter = x;
ycenter = y;
radius = r;
}

public MyCircle(MyCircle obj)//construct clone of an object , pass object to


constructor
{
xcenter = obj.xcenter;
ycenter = obj.ycenter;
radius = obj.radius;
}
public double area( )
{
return (3.14*radius*radius);
}
public double perimeter( )
{
return (2*3.14*radius);
}
public void changeTheRadius(int r)
{
radius = r ; // or this.radius r, explicit parameter
}
Engr. Sidra Shafi Lab-07 1
3rdSemester Lab-07: Constructor and Method Overloading

public void output( ) // this method prints all values


{
System.out.println("center: " + xcenter + "," + ycenter +
" radius: " + radius);
}
}
public class Constructor_Overloading {

public static void main(String[] args) {


MyCircle circle1, circle2,circle3;
circle1 = new MyCircle(3, 4, 10); // instantiation i.e. declaration
of Mycircle objects
circle2 = new MyCircle( );
circle1.output( );
circle2.output( );

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( );

circle1 = new MyCircle(13, 14, 100);


circle1.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.

Engr. Sidra Shafi Lab-07 2


3rdSemester Lab-07: Constructor and Method Overloading

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.

Why Java Does Not Support a Static Constructor:


When we mark anything with a static keyword, it belongs to class only, for example, static
method, static variable, etc. Static methods cannot be inherited from their subclasses because
they belong to the class in which they are declared. Similarly, we cannot use a static variable
in its subclasses.
If the constructors are marked as static, they cannot be called from the child class; thus, the
child class's object will not be created.

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 ;

Engr. Sidra Shafi Lab-07 3


3rdSemester Lab-07: Constructor and Method Overloading

}
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

//swapping example to demonstrate Pass by Value and Pass by Reference


public class c1 {
public static void main(String[] args) {
int a = 30;
int b = 45;
System.out.println("Before swapping, a = " +
a + " and b = " + b);
// Invoke the swap method
swapFunction(a, b);
System.out.println("\n**Now, Before and After swapping values will
be same here**:");
System.out.println("After swapping, a = " +
a + " and b is " + b);
}
public static void swapFunction(int a, int b) {

Engr. Sidra Shafi Lab-07 4


3rdSemester Lab-07: Constructor and Method Overloading

System.out.println("Before swapping(Inside), a = " + a


+ " b = " + b);
// Swap n1 with n2
int c = a;
a = b;
b = c;
System.out.println("After swapping(Inside), a = " + a
+ " b = " + b);
}
}

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

Engr. Sidra Shafi Lab-07 5


3rdSemester Lab-07: Constructor and Method Overloading

allowed operation on the Record that it already references.

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.

Returning Objects from Methods:


A method can return any type of data, including class types that you create.

Example:
public class RecordDemo {

public static void main(String[] args) {

Record id = new Record();

Record obj= id.createRecord(16, "Sidra");


System.out.println("After method call: "+"name ->"+obj.name + " " +"id
->"+ obj.num);
Record obj2= obj.createRecord(17, "Saleem");
System.out.println("After method call: "+"name ->"+obj2.name + " "
+"id ->"+ obj2.num);

}
}

class Record
{
int num;
String name;

public Record createRecord(int n, String name)


{
Record r = new Record();
r.num = n;
r.name = name;
return r;
}
}

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.

Syntax: static data_type member1_name; //static variable declaration


Engr. Sidra Shafi Lab-07 6
3rdSemester Lab-07: Constructor and Method Overloading

Syntax: static return_type method_name(parameters) //static method declaration


{
//statements;
}

Ex: class class_name


{
static data_type member1_name; //static variable
::
static return_type method_name(parameters); //static method
{
//statements;
}}
Example:

//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

Lab Task Marks: 10

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:

1. Overload the constructor 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.

Engr. Sidra Shafi Lab-07 7


3rdSemester Lab-07: Constructor and Method Overloading

(Random Numbers Generation:

Using Random class: To use the Random Class to generate random numbers, follow the
steps below:

1. Import the class java.util.Random


2. Make the instance of the class Random, i.e., Random rand = new Random()
3. Invoke one of the following methods of rand object:

nextInt(upperbound) generates random numbers in the range 0 to upperbound-1.


)

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.
//*******************************************************

public class Account


{
private double balance;
private String name;
private long acctNum;

//----------------------------------------------
//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

// If so, decrements balance by amount; if not, prints


message.
//----------------------------------------------
public void withdraw(double amount)
{
if (balance >= amount)
balance -= amount;
else
System.out.println("Insufficient funds");
}

//----------------------------------------------
// 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;

public class TestAccount


{
public static void main(String[] args)
Engr. Sidra Shafi Lab-07 9
3rdSemester Lab-07: Constructor and Method Overloading

{
String name;
double balance;
long acctNum;
Account acct;

Scanner scan = new Scanner(System.in);

System.out.println("Enter account holder's first name");


name = scan.next();
acct = new Account(name);
System.out.println("Account for " + name + ":");
System.out.println(acct);

System.out.println("\nEnter initial balance");


balance = scan.nextDouble();
acct = new Account(balance,name);
System.out.println("Account for " + name + ":");
System.out.println(acct);

System.out.println("\nEnter account number");


acctNum = scan.nextLong();
acct = new Account(balance,name,acctNum);
System.out.println("Account for " + name + ":");
System.out.println(acct);

System.out.print("\nDepositing 100 into account, balance


is now ");
acct.deposit(100);
System.out.println(acct.getBalance());
System.out.print("\nWithdrawing $25, balance is now ");
acct.withdraw(25);
System.out.println(acct.getBalance());
System.out.print("\nWithdrawing $25 with $2 fee, balance
is now ");
acct.withdraw(25,2);
System.out.println(acct.getBalance());

System.out.println("\nBye!");
}
}

Opening and Closing Accounts:


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 write the following additional code:

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;

public class TestAccounts1 {


public static void main(String[] args) {
Account testAcct;

Scanner scan = new Scanner(System.in);


System.out.println("How many accounts would you like to create?");
int num = scan.nextInt();

for (int i=1; i<=num; i++) {


testAcct = new Account(100, "Name" + i);
System.out.println("\nCreated account " + testAcct);
System.out.println("Now there are " + Account.numAccounts() + " accounts");
} }}
Engr. Sidra Shafi Lab-07 11
3rdSemester Lab-07: Constructor and Method Overloading

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.

You can take elements from ArrayList as follows:

Account acc1 = acct_holders.get(0); //element at index 0

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
**********

Engr. Sidra Shafi Lab-07 12

You might also like