0% found this document useful (1 vote)
182 views20 pages

Lab 02 09-03-2021

This document outlines a lab manual for an Object Oriented Programming lab in Java. The lab focuses on method and constructor overloading concepts as well as parameters, instance variables, and class variables. It provides examples of passing arguments by value versus reference and using the 'this' keyword. It also introduces packages and tasks students with modifying a class to be part of a package and testing it from outside the package. The document concludes with tasks to write functions for generating random numbers, calculating averages, and solving quadratic equations.

Uploaded by

Muhammad Faizan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (1 vote)
182 views20 pages

Lab 02 09-03-2021

This document outlines a lab manual for an Object Oriented Programming lab in Java. The lab focuses on method and constructor overloading concepts as well as parameters, instance variables, and class variables. It provides examples of passing arguments by value versus reference and using the 'this' keyword. It also introduces packages and tasks students with modifying a class to be part of a package and testing it from outside the package. The document concludes with tasks to write functions for generating random numbers, calculating averages, and solving quadratic equations.

Uploaded by

Muhammad Faizan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA

FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

COMPUTER ENGINEERING DEPARTMENT

Object Orienting Programming


(Java)

Lab Manual No 02

Dated:
09 Mar, 2021 to 16th Mar, 2021
th

Semester:
Spring 2021

Lab Instructor: SHEHARYAR KHAN Page 1


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

COMPUTER ENGINEERING DEPARTMENT

Parameters, Method and Constructor Overloading:

Lab Objective:
This lab focuses on the concept of “Functions with parameters and return types”. Also, it includes
concepts related to method and constructor overloading. All the assignments should be completed
in this lab.
Parameters
Variables should be initialized where they are declared and they should be declared in the smallest
scope possible. A null initialization is acceptable. Variable names should be short yet meaningful.

What is Actually Passed to a Method?


What is passed "to" a method is referred to as an "argument". The "type" of data that a method can
receive is referred to as a "parameter". (You may see "arguments" referred to as "actual parameters"
and "parameters" referred to as "formal parameters".)
First, notice that if the arguments are variable names, the formal parameters need not be those same
names (but must be the same data type).

Pass-by-value
means that when a method is called, a copy of the value of each argument is passed to the method.
This copy can be changed inside the method, but such a change will have NO effect on the argument.

Lab Instructor: SHEHARYAR KHAN Page 2


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

COMPUTER ENGINEERING DEPARTMENT

Example No 1:
Will the values from main be changed after being sent to this method??

public class parameters {


public static void main(String args[]){
int num = 10;
double decimal = 5.4;

NumberManeuvers(num, decimal);

System.out.println("num = " + num + "and decimal = " + decimal);

}
public static void NumberManeuvers(int i, double j)
{
if (i == 10)
j = 6.2;
i = 12;

//System.out.println(i+" "+j); // Here Value Change


}
}

Instance variables:
These variables belong to the instance of a class, thus an object. And every instance of that class (object)
has it's own copy of that variable. Changes made to the variable don't reflect in other instances of that
class.
Example 02 :

public class InstanceVariable {


public int Barcode; // Instance Variable

public static void main(String[] args) {


InstanceVariable prod1 = new InstanceVariable();
prod1.Barcode = 123456;

InstanceVariable prod2 = new InstanceVariable();


prod2.Barcode = 987654;

System.out.println(prod1.Barcode);
System.out.println(prod2.Barcode);
}

Lab Instructor: SHEHARYAR KHAN Page 3


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

COMPUTER ENGINEERING DEPARTMENT

Class Variable:
These are also known as static member variables and there's only one copy of that variable that is
shared with all instances of that class. If changes are made to that variable, all other instances will see
the effect of the changes.

public class ClassVariableExample {

public static int Barcode; // Class Variable

public int getBarcode() {

return Barcode;
}

public void setBarcode(int value){


Barcode = value;
}
public static void main(String[] args) {

ClassVariableExample prod1 = new ClassVariableExample();


prod1.setBarcode(123456);
ClassVariableExample prod2 = new ClassVariableExample();
prod2.setBarcode(987654);

System.out.println(prod1.getBarcode());
System.out.println(prod2.getBarcode());
}
}

What is “this”:

this is a keyword in Java. It can be used inside the Method or constructor of Class. It (this) works as a
reference to the current Object whose Method or constructor is being invoked. The this keyword can be
used to refer to any member of the current object from within an instance Method or a constructor.

this keyword with field (Instance Variable): this keyword can be very useful in the handling of Variable
Hiding. We cannot create two instance/local variables with the same name. However, it is legal to create
one instance variable & one local variable or Method parameter with the same name. In this scenario,
the local variable will hide the instance variable this is called Variable Hiding.

Lab Instructor: SHEHARYAR KHAN Page 4


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

COMPUTER ENGINEERING DEPARTMENT

Example of Variable Hiding:

class JBT {

int variable = 5;

public static void main(String args[]) {


JBT obj = new JBT();

obj.method(20);
obj.method();
}

void method(int variable) {


variable = 10;
System.out.println("Value of variable :" + variable);
}

void method() {
int variable = 40;
System.out.println("Value of variable :" + variable);
}
}

As you can see in the example above the instance variable is hiding and the value of the local variable
(or Method Parameter) is displayed not instance variable. To solve this problem, use this keyword with a
field to point to the instance variable instead of the local variable.

void method(int variable) {


variable = 10;
System.out.println("Value of variable :" + this.variable);
}

void method() {
int variable = 40;
System.out.println("Value of variable :" + this.variable);
}
}

Lab Instructor: SHEHARYAR KHAN Page 5


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

COMPUTER ENGINEERING DEPARTMENT

Package Introduction:

Java applications often comprise a very large number of classes. In order to provide for
management of all these classes, they are arranged into groupings known as packages, with each
package containing a logical group of related classes.

Existing Java Packages are available at the following link:


http://tns-www.lcs.mit.edu/manuals/java-api-old/packages.html
We are using java.lang in this lab. The class index of the java.lang package is available at
the link:
http://tns-www.lcs.mit.edu/manuals/java-api-old/java.lang.html
To use any class of the package we have to first import that class. For instance, to import Math
class from the Lang Package we will use the following code:
import java.lang.Math;
The class Math contains methods for performing basic numeric operations such as the elementary
exponential, logarithm, square root, and trigonometric functions.
The index of methods and variable of java.lang.Math is available at the link
http://tns-www.lcs.mit.edu/manuals/java-api-old/java.lang.Math.html#_top_

User Defined Package


1. File→ New→ Package . Name it myPackage
2. Define a Class ImpExample.
3. In class definition declare a variable and Intialize to 5.
4. Save It .
5. Create another Class PrintImp in the Package named as myPackage .
6. Create a Object of ImpExampe and Print the value .

Example:
package myPackage; package myPackage;

public class ImportExample { public class PrintImp {


int var=5; public static void main(String abc[]){
ImportExample e=new ImportExample();
} System.out.println(e.var);
}

Lab Tasks:
Modify the following class to make it a part of the package named myutil. In addition to
adjusting the source file, what are the steps you need to take so that the class becomes
usable/accessible from other classes that are outside of this myutil package?

Lab Instructor: SHEHARYAR KHAN Page 6


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

COMPUTER ENGINEERING DEPARTMENT

Write a program that tests the Person class defined in above program. Place this test
program outside of the myutil package and make sure you can call the constructor and the
methods of the Person class correctly.
➢ Write a class with the following functions:
➢ Function that returns a random number which lies in the range x to y.
Where, x and y passed as parameters.

➢ Function that returns the average (rounded off up to 2 decimal places) of a student
who scored marks in the courses passed as parameters.
➢ Function the returns the solution of the quadratic equation: 2.7x2+ 5.9x +2.8

Lab Instructor: SHEHARYAR KHAN Page 7


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

COMPUTER ENGINEERING DEPARTMENT

➢ Function the returns the Channel Capacity using the following formula: C =
Blog2M Where, B (Bandwith) and M (Number of levels) are passed as parameters.
➢ Function that takes a parameter x is in degrees, calculate the cos, sin and tan
function.

➢ Calculate Volume
➢ Write a source class that sends the height and radius to the cylinder class and
prints the returned values of area and volume of the cylinder.

Method Overloading:

Method overloading is having multiple methods with same name but different signature. Method
signature includes method name, list of parameters and types of parameters. Following hint clears
the concept of method overloading.

Lab Instructor: SHEHARYAR KHAN Page 8


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

COMPUTER ENGINEERING DEPARTMENT

Example:

Constructor Overloading
Constructor overloading is having multiple constructors with same name as class name but
different list of parameters. Following hint (given on next page) clear about constructor
overloading.

Lab Tasks:
Perform assignment2 involving method overloading. Use method overloading pass
different values to “r” and “h”. (By passing single argument, two arguments)
Perform assignment2 involving constructor overloading. Use constructor overloading pass
different values to “r” and “h”.

Lab Instructor: SHEHARYAR KHAN Page 9


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

COMPUTER ENGINEERING DEPARTMENT

Lab Instructor: SHEHARYAR KHAN Page 10


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

COMPUTER ENGINEERING DEPARTMENT

Accessors and Mutators


One of the ways we can enforce data encapsulation is through the use of accessors and mutators. The
role of accessors and mutators are to return and set the values of an object's state. This article is a
practical guide on how to program them in Java.

As an example, I'm going to use a Person class with the following state and constructor already defined:

public class Person {

//Private fields
private String firstName;
private String middleNames;
private String lastName;
private String address;
private String username;

//Constructor method
public Person(String firstName, String middleNames, String lastName, String address)
{
this.firstName = firstName;
this.middleNames = middleNames;
this.lastName = lastName;
this.address = address;
this.username = "";
}
}

ACCESSOR METHODS

An accessor method is used to return the value of a private field. It follows a naming scheme prefixing
the word "get" to the start of the method name. For example let's add accessor methods for firstname,
middleNames and lastname:

//Accessor for firstName


public String getFirstName()
{
return firstName;
}

//Accessor for middleNames


public String getMiddlesNames()

Lab Instructor: SHEHARYAR KHAN Page 11


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

COMPUTER ENGINEERING DEPARTMENT

{
return middleNames;
}

//Accessor for lastName


public String getLastName()
{
return lastName; }

These methods always return the same data type as their corresponding private field (e.g., String) and
then simply return the value of that private field.

We can now access their values through the methods of a Person object:

public class PersonExample {

public static void main(String[] args) {

Person dave = new Person("Shery", "Ayesha", "Davidson", "12 Pall Mall");


System.out.println(dave.getFirstName() + " " + dave.getMiddlesNames() + " " + dave.getLastName());
}
}

MUTATOR METHODS

A mutator method is used to set a value of a private field. It follows a naming scheme prefixing the word
"set" to the start of the method name. For example, let's add mutator fields for address and username:

//Mutator for address


public void setAddress(String address)
{
this.address = address;
}

//Mutator for username


public void setUsername(String username)
{
this.username = username;
}

These methods do not have a return type and accept a parameter that is the same data type as their
corresponding private field. The parameter is then used to set the value of that private field.

Lab Instructor: SHEHARYAR KHAN Page 12


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

COMPUTER ENGINEERING DEPARTMENT

It's now possible to modify the values for the address and username inside the Person object:

public class PersonExample {

public static void main(String[] args) {

Person dave = new Person("Dave", "Bob Bill", "Davidson", "12 Pall Mall");
dave.setAddress("256 Bow Street");
dave.setUsername("DDavidson");

}
}

WHY USE ACCESSORS AND MUTATORS?

It's easy to come to the conclusion that we could just change the private fields of the class definition to
be public and achieve the same results. It's important to remember that we want to hide the data of the
object as much as possible. The extra buffer provided by these methods allows us to:

• change how the data is handled behind the scenes


• impose validation on the values that the fields are being set to.

Let's say we decide to modify how we store middle names. Instead of just one String we now use an
array of Strings:

private String firstName;


//Now using an array of Strings
private String[] middleNames;
private String lastName;
private String address;
private String username;

public Person(String firstName, String middleNames, String lastName, String address)


{
this.firstName = firstName;

//create an array of Strings


this.middleNames = middleNames.split(" ");
this.lastName = lastName;
this.address = address;
this.username = "";
}

Lab Instructor: SHEHARYAR KHAN Page 13


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

COMPUTER ENGINEERING DEPARTMENT

//Accessor for middleNames


public String getMiddlesNames()
{
//return a String by appending all the Strings of middleNames together
StringBuilder names = new StringBuilder();

for(int j=0;j < (middleNames.length-1);j++)


{
names.append(middleNames[j] + " ");
}
names.append(middleNames[middleNames.length-1]);
return names.toString();
}

The implementation inside the object has changed but the outside world is not affected. The way the
methods are called remains exactly the same:

public class PersonExample {

public static void main(String[] args) {

Person dave = new Person("Dave", "Bob Bill", "Davidson", "12 Pall Mall");
System.out.println(dave.getFirstName() + " " + dave.getMiddlesNames() + " " + dave.getLastName());
}
}

Or, let's say the application that is using the Person object can only accept usernames that have a
maximum of ten characters. We can add validation in the setUsername mutator to make sure the
username conforms to this requirement:

public void setUsername(String username)


{
if (username.length() > 10)
{
this.username = username.substring(0,10);
}
else
{
this.username = username;
}
}

Lab Instructor: SHEHARYAR KHAN Page 14


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

COMPUTER ENGINEERING DEPARTMENT

Now if the username passed to the setUsername mutator is longer than ten characters it is
automatically truncated.

Using Javadoc Comments for Class Documentation

1. Open the Eclipse project folder.


2. Select Project > Generate Javadoc... .

3. At first step of the wizard, you can define settings for:

3.1. Select path for the javadoc.exe tool from the JDK.
3.2. Project resources for which to generate Javadoc.
3.3. Classes and methods for which to generate Javadoc based on their visibility.
3.4. Location of the Javadoc (by default it will be placed in the doc folder in the project
location).

Lab Instructor: SHEHARYAR KHAN Page 15


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

COMPUTER ENGINEERING DEPARTMENT

4. At second step you can make settings regarding:

4.1. Document title.


4.2. Documentation structure.
4.3. Select document tags to be processed.
4.4. Other resources (archives, projects) used in project to be included in the
documentation.
4.5. Select CSS style sheet for your documentation.

Lab Instructor: SHEHARYAR KHAN Page 16


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

COMPUTER ENGINEERING DEPARTMENT

5. At the last step you can save the settings in an Ant script for future use.

Lab Instructor: SHEHARYAR KHAN Page 17


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

COMPUTER ENGINEERING DEPARTMENT

Lab Tasks
Question No.01:
Write a program that computes the total ticket sales of a concert. There are three types of
seating: A, B, and C. The program accepts the number of tickets sold and the price of a
ticket for each of the three types of seats. The total sales are computed as follows:
totalSales = numberOfA_Seats * pricePerA_Seat + numberOfB_Seats *
pricePerB_Seat +numberOfC_Seats * pricePerC_Seat
Question No.02:
Write this program, using only one class, the main class of the above program. Define a
new class named Temperature. The class has two accessors—to-Fahrenheit and
toCelsius—that return the temperature in the specified unit and two mutators—
setFahrenheit and setCelsius—that assign the temperature in the specified unit. Maintain
the temperature internally in degrees Fahrenheit.
Question No.03
Using this class, write a program that inputs temperature in degrees Fahrenheit and
outputs the temperature in equivalent degrees Celsius.
Question No.04
Create the following figure using World and Turtle classes. You have to use three different
turtles to draw each shape. Make a class MyWorld. Draw three methods createSq(),
createTri() and createRect() class. Write the codes for creating square, triangle and
rectangle in the createSq(), createTri() and createRect() methods respectively. Make a
constructor that instantiate the World class. Turtle class should be instantiated in each
method separately. Make the main() method, create an object of MyWorld class and call all
the three methods.

Lab Instructor: SHEHARYAR KHAN Page 18


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

COMPUTER ENGINEERING DEPARTMENT

Question No.05
Design a class that keeps track of a student’s food purchases at the campus cafeteria. A
meal card is assigned to an individual student. When a meal card is first issued, the balance
is set to the number of points. If the student does not specify the number of points, then the
initial balance is set to 100 points. Points assigned to each food item are a whole number.
A student can purchase additional points at any time during a semester. Every time food
items are bought, points are deducted from the balance. If the balance becomes negative,
the purchase of food items is not allowed. There is obviously more than one way to
implement the MealCard class. Any design that supports the key functionalities is
acceptable. Put this class in the myutil package.

Question No.06
Write a program that tests the meal card class defined in above program. Define this test
program outside the myutil package. Create one or two meal card objects in the test
program and verify that all methods defined in the meal card class operate correctly.
Question No.07
Add javadoc comments to the following class.
classInstructor {
privateString name;
public voidsetName(String name){
this.name = name;
}
publicString getName(){
returnname;
}
}

3. What is the purpose of @authortag?


4.

Lab Instructor: SHEHARYAR KHAN Page 19


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

COMPUTER ENGINEERING DEPARTMENT

Question No.08
Copy the Code from Book Page 410-418 and generate Java Doc?
Question No.09
Complete the following constructor.
classStudent {
privateString name;
private int age;
privateAddress address;
publicStudent(String name,intage, Address address){
//assign passed values to the data members
}

Question No.10
Consider the following class.

classModifier {
public static change(int x, int y){
x = x - 10;
y = y + 10;
}
}
What will be an output from the following code?
Int x = 40;
Int y = 20;
Modifier.change(x,y);
System.out.println("x = "+ x);
System.out.println("y = "+ y);

The End

Lab Instructor: SHEHARYAR KHAN Page 20

You might also like