0% found this document useful (0 votes)
77 views13 pages

Lab-07 Muneeb Asif 334492

This document provides instructions for Lab 07 on fundamentals of object-oriented programming. It includes activities to understand classes and objects, access specifiers, constructors, getters/setters, and static members. The activities create a Circle class with radius and color attributes and methods to get radius, get area, and construct circles. A TestCircle class is used to test the Circle class. Later activities cover static variables, passing objects to methods, and storing objects in arrays.

Uploaded by

Muneeb Asif
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 (0 votes)
77 views13 pages

Lab-07 Muneeb Asif 334492

This document provides instructions for Lab 07 on fundamentals of object-oriented programming. It includes activities to understand classes and objects, access specifiers, constructors, getters/setters, and static members. The activities create a Circle class with radius and color attributes and methods to get radius, get area, and construct circles. A TestCircle class is used to test the Circle class. Later activities cover static variables, passing objects to methods, and storing objects in arrays.

Uploaded by

Muneeb Asif
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/ 13

Department of Computing

CS 212: Object Oriented Programming

Class: BESE-11AB
Lab 07: Fundamentals of OOP

Date: 21/04/2021

Instructor: Ms. Hania Aslam

CS 212: Object Oriented Programming Page 1


Learning Objectives

The learning objectives of this lab is to understand and practice the fundamental concepts of
object-oriented programming, such as classes and objects, access specifiers, constructors,
setters/getters & static members.

Activity #1
This first exercise shall lead you through all the basic concepts discussed in previous lectures
related to classes and objects. Please go through the complete activity and make the necessary
modifications at each step wherever required.

A class called Circle is designed which contains:

• Two private instance variables: radius (of the type double) and color (of the type String),
with default value of 1.0 and "red", respectively.
• Two overloaded constructors - a default constructor with no argument, and a constructor
which takes a double argument for radius.
• Two public methods: getRadius() and getArea(), which return the radius and area of this
instance, respectively.

/*
* The Circle class models a circle with a radius and color.
*/
public class Circle {
// Save as "Circle.java"
// private instance variable, not accessible from outside this
//class
private double radius;
private String color;

// The default constructor with no argument.


// It sets the radius and color to their default value.
public Circle() {
radius = 1.0;
color = "red";
}

// 2nd constructor with given radius, but color default


public Circle(double r) {
radius = r;
color = "red";
}

// A public method for retrieving the radius


public double getRadius() {

CS 212: Object Oriented Programming Page 2


return radius;
}

// A public method for computing the area of circle


public double getArea() {
return radius*radius*Math.PI;
}
}

Compile "Circle.java". Can you run the Circle class? Why or why not?

Answer:

No we cannot run Circle class only, as it don’t have main method inside it. We can only run a
.java file if it has main method inside it. Its mandatory to have Main method in order to run tha
.java file.

Let us write a test program called TestCircle (in another source file
called TestCircle.java) which uses the Circle class, as follows:
public class TestCircle {

// Save as "TestCircle.java"

public static void main(String[] args) {

// Declare an instance of Circle class called c1.


// Construct the instance c1 by invoking the "default" constructor
// which sets its radius and color to their default value.

Circle c1 = new Circle();

// Invoke public methods on instance c1, via dot operator.


System.out.println("The circle has radius of "
+ c1.getRadius() + " and area of " + c1.getArea());

// Declare an instance of class circle called c2.


// Construct the instance c2 by invoking the second constructor
// with the given radius and default color.

CS 212: Object Oriented Programming Page 3


Circle c2 = new Circle(2.0);
// Invoke public methods on instance c2, via dot operator.
System.out.println("The circle has radius of "
+ c2.getRadius() + " and area of " + c2.getArea());}}

Now, run the TestCircle and observe the results.

As a next step, incorporate the following changes into your code:

1. Constructor: Modify the class Circle to include a third constructor for constructing
a Circle instance with two arguments - a double for radius and a String for color.
Modify the test program TestCircle to construct an instance of Circle using this
constructor.

Test Public/Private Access Modifiers

2. public vs. private: In TestCircle, can you access the instance variable radius directly
(e.g., System.out.println(c1.radius)); or assign a new value to radius (e.g., c1.radius=9.0)?
Try it out and explain the error messages.

NO we cannot access the field radius of class Circle inside the TestCircle class because we kept
the field radius of class Circle as private.So, its only visible and accessible inside the Circle class
if we try to access it outside te Circle class anywhere in the package TestClass it would give an
error that Radius is private you field of Class Circle you canit access it in TestClass

3. Setter: Is there a need to change the values of radius and color of a Circle instance after it
is constructed? If yes then in that case we cannot directly change the private data
members and we are in need of public functions that can help us achieve that purpose.
Add two public setter methods for changing the radius and color fields of a Circle
instance .
Yes ,one may wants too change the value of field of class once they have been initialized through
constructor in this case we take the help of setter methods to access the fields in directly

CS 212: Object Oriented Programming Page 4


4. Getter: If we want to directly access the values of the data members then we can do that
with the help of getter functions. Add a getter method for variable color and one for
radius for retrieving the color and radius of this instance.

Modify the test program to test the newly created getter and setter methods.

Code for calling getters and setters inside TestCircle class:

Output of code:

CS 212: Object Oriented Programming Page 5


Static Variables Vs. Instance Variables

In the class we have discussed about the static and instance variables. Modify the Circle class
created above by adding a static variable NoOfObjects to calculate the total objects instantiated
by the class. Create 5 objects of the circle class and display the resultant value of the static
variable NoOfObjects.

Code for Static variable no_of_objects:

CS 212: Object Oriented Programming Page 6


Activity #2.
Analyze and briefly explain the output of the following program:
public class Test
{
public static void main(String[] args)
{
Circle circle1 = new Circle(1);
Circle circle2 = new Circle(2);

swap1(circle1, circle2);
System.out.println("After swap1: circle1 = " +
circle1.radius + " circle2 = " + circle2.radius);

swap2(circle1, circle2);
System.out.println("After swap2: circle1 = " +
circle1.radius + " circle2 = " + circle2.radius);
}
public static void swap1(Circle x, Circle y)
{
Circle temp = x;
x = y;
y = temp;
}

public static void swap2(Circle x, Circle y)


{
double temp = x.radius;
x.radius = y.radius;
y.radius = temp;
}
}
class Circle
{
double radius;

Circle(double newRadius)
{
radius = newRadius;
}
}
You may like to have a look at: http://www.geeksforgeeks.org/swap-exchange-objects-java/

CS 212: Object Oriented Programming Page 7


Answer:

The code given above is used to swap the radius of two circle object of class circle In first swap no
change in radius of two circle x and y would occur .However in second swap the radius of two circles
will inter change with each other so that the radius of circle x which we initialize with 1 becomes
2.And the radius of circle y which we initialize with 2 becomes 1.

Task #1:

Create a class SavingsAccount . Use a static variable annualInterestRate to store the annual
interest rate for all account holders. Each object of the class contains a private instance variable
savingsBalance indicating the amount the saver currently has on deposit. Provide method
calculateMonthlyInterest to calculate the monthly interest by multiplying the savingsBalance by
annualInterestRate divided by 12—this interest should be added to savingsBalance.

Provide a static method modifyInterestRate that sets the annualInterestRate to a new value. Write
a program to test class SavingsAccount. Instantiate two savingsAccount objects, saver1 and
saver2, with initial balance of $3200.00 and $4500.00, respectively. Set annualInterestRate to
5%, then calculate the monthly interest for each of 12 months and print the new balances for both
savers. Next, set the annualInterestRate to 7%, calculate the next month’s interest and print the
new balances for both savers.

CS 212: Object Oriented Programming Page 8


Screenshots of code:

CS 212: Object Oriented Programming Page 9


CS 212: Object Oriented Programming Page 10
Screenshots of output:

Task #2:

As we have discussed earlier, in Java, arrays are capable of storing objects as well. Create a class
Student that contains two private fields: student_id & marks(0-100). Provide appropriate
constructors/methods for this class. Next, create an array named studentArray that is capable of
storing record for seven students. Initialize all array objects with values of your choice(
Remember, Student is a reference type i.e: each array element stores a reference to the Student
object ). Finally, iterate over all elements of the studentArray in order to calculate and display the
average marks.

Screenshots of code:
CS 212: Object Oriented Programming Page 11
Screenshots of output:

CS 212: Object Oriented Programming Page 12


Hand in

Hand in the source code from this lab at the appropriate location on the LMS system.
1) All completed java source code neatly placed into labeled text boxes representing the
work accomplished for this lab. The code should contain necessary comments.

To Receive Credit

1. Comment your program heavily. Intelligent comments and a clean, readable formatting
of your code account for 20% of your grade.

2. The lab time is not intended as free time for working on your programming/other
assignments.

CS 212: Object Oriented Programming Page 13

You might also like