0% found this document useful (0 votes)
43 views9 pages

Java OOP Lab: Classes and Methods

Lab 05_Classes, Objects and Methods (1)

Uploaded by

am7483823
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views9 pages

Java OOP Lab: Classes and Methods

Lab 05_Classes, Objects and Methods (1)

Uploaded by

am7483823
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

NUML

National
University of modern
Language Islamabad
2ndSemester Lab-05: Classes, Objects and Methods in Java

Lab no. 5

OOP lab
Name Hamdan Ashar
Rollno. I_se_9244427

2nd semester (afternoon)


(Scetion A)

Submittted To
Dr. Bilal Bajwa

Dr. M. Bilal Shahnawaz Lab-05 1


2ndSemester Lab-05: Classes, Objects and Methods in Java

Laboratory 05: Classes, Objects and Methods


Statement Purpose:
At the end of this lab, the students should be able to:
 Create class
 Create object
 Create method

Implementing Java classes, objects and methods:

A Simple class:
Consider the following code, there is a class called Box that defines three instance variables: width,
height, and depth. Currently, this class does not contain any methods.

class Box {
double width;
double height;
double depth;
}

This is a complete program that uses the Box class:


//A Program that uses the Box class.
public class Box {
double width;
double height;
double depth;
}
//This class declares an instance of type Box.
public class boxTest {
public static void main(String[] args) {
Box mybox=new Box();
double vol;

//assign values to mybox's instance variables


[Link]=10;
[Link]=20;
[Link]=15;

//compute volume of box


vol=[Link]*[Link]*[Link];

[Link]("Volume is " + vol);


}
}

Output:

Volume is 3000.0

Adding a Method to the BoxClass:


//This program includes a method inside the box class.
public class Box {
double width;
double height;

Dr. M. Bilal Shahnawaz Lab-05 1


2ndSemester Lab-05: Classes, Objects and Methods in Java

double depth;

void volume(){
[Link]("Volume is ");
[Link](width*height*depth);
}
}
//This class declares an instance of type Box.
public class boxTest {
public static void main(String[] args) {
Box mybox1=new Box();
Box mybox2=new Box();
double vol;

//assign values to mybox1's instance variables


[Link]=10;
[Link]=20;
[Link]=15;

//assign different values to mybox2's instance variables


[Link]=3;
[Link]=6;
[Link]=9;

//display volume of first box


[Link]();

//display volume of first box


[Link]();
}
}

Output:

Volume is 3000.0
Volume is 162.0

Adding a Method which returns a value:

Consider the following code, in which we create a box class with its instance variables: width, height
and depth. This class also defines a method called volume.
Another class called DemoBox is also created, which encapsulates main method. In this class, objects
of class Box are created and with the help of these objects methods of Box class are called as
object_name.volume(), which returns the calculated volume.

Code:
//A program that uses the Box class.
//This program includes a method inside the box class which returns the
volume of a box.
public class Box {
double width;
double height;
double depth;

double volume()
{
return width*height*depth;
}

Dr. M. Bilal Shahnawaz Lab-05 2


2ndSemester Lab-05: Classes, Objects and Methods in Java

}
//This class declares two objects of type Box.
public class boxTest {
public static void main(String[] args) {
Box mybox1=new Box();
Box mybox2=new Box();
double vol;

//assign values to mybox1's instance variables


[Link]=10;
[Link]=20;
[Link]=15;

//assign different values to mybox2's instance variables


[Link]=3;
[Link]=6;
[Link]=9;

vol=[Link]();
[Link]("Volume is " + vol);

//get volume of second box


vol=[Link]();
[Link]("Volume is " + vol);
}
}

Output:
Volume is 3000.0
Volume is 162.0

Adding a Method that Takes Parameters

Add the following parameterized method in Box class.

//sets dimensions of box


void setDim(double w, double h, double d)
{
width=w;
height=h;
depth=d;
}

Also, in DemoBox class, replace the following code


//assign values to mybox1’s instance variables
[Link]=10;
[Link]=20;
[Link]=15;

// assign different values to mybox2’s instance variables


[Link]=3;
[Link]=6;
[Link]=9;

with the code given below


//initialize each box
[Link](10,20,15);
[Link](3,6,9);

Dr. M. Bilal Shahnawaz Lab-05 3


2ndSemester Lab-05: Classes, Objects and Methods in Java

After changes in code, following output will be shown in Eclipse:


Output:

Volume is 3000.0
Volume is 162.0

Lab Tasks:
Task 1: Marks: 2

Define a class addressBook. It has three attributes name, address, and phone. It must have methods
showName (), showAddress (), and showPhone() with return type void. Show methods will show the
values of attributes only. Your name, address, & phone number to the class attributes can be set
directly using syntax [Link]. Make another class having the main () method,
make object of class adddressBook and print values of name, address and phone using these methods.

Code
ackage Hamdan1;

public class addressBook {


String name;
String address;
long phone;

void showName() {
[Link]("Name: " + name);
}
void showAddress() {
[Link]("Address: " + address);
}
void showPhone() {
[Link]("Phone: " + phone);
}

package Hamdan1;

public class bookmain {

public static void main(String[] args) {


addressBook myContact = new addressBook();

[Link] = "HAMDAN";
[Link] = "NUML H9, ISLAMABAD";
[Link] = 0312-1234567;
[Link]();
[Link]();
[Link]();
}

}
Output

Dr. M. Bilal Shahnawaz Lab-05 4


2ndSemester Lab-05: Classes, Objects and Methods in Java

Task 2: Marks: 4

Make a class Rectangle which calculates the area and perimeter of rectangle according to the
following algorithm.
Step1: Declare two variables length and width of type double.
Step2: Make a Parameterize method which sets the length and width according to the values it
receives as parameters.
Step 3: Make two methods getLength and getWidth which only return length and width. Their return
type is double.
Step 4: Make a method perimeter which calculates the perimeter according to the formula 2*L+2*W.
Step 5: Make a method area which calculates the area according to the formula L*W.
Step 6: Make a class RectDemo which encapsulates main method. Make an object of Rectangle class.
Step 7: Get and Print the length and width of Rectangle by using appropriate methods.
Step 8: Print the Perimeter and Area of Rectangle.

Code
package Hamdan1;

class Rectangle {
private double length;
private double width;

void setDimensions(double len, double wid) {


length = len;
width = width;
}
double getLength() {
return length;
}

double getWidth() {
return width;
}

double perimeter() {
return 2 * length + 2 * width;
}
double area() {
return length * width;
}
}
---------------------------------------------------------------------------
-----
package Hamdan1;

public class RectangleDemo {

public static void main(String[] args) {


Rectangle myRectangle = new Rectangle();

[Link](10.5, 7.2);

[Link]("Length: " + [Link]());


[Link]("Width: " + [Link]());

[Link]("Perimeter: " + [Link]());


Dr. M. Bilal Shahnawaz Lab-05 5
2ndSemester Lab-05: Classes, Objects and Methods in Java

[Link]("Area: " + [Link]());


}}
Output

Task 3: Marks: 4

Write a program that has variables to store Car data like; CarModel, CarName, CarPrice and
CarOwner. The program should include functions to assign user defined values to the above
mentioned variable and a display function to show the values. Write a main that calls these functions.
Now write another runner class that declares three Car objects and displays the data of all three.

Code
package Hamdan1;

public class CarRecord {


class Car {
String CarModel;
String CarName;
double CarPrice;
String CarOwner;

void setCarData(String model, String name, double price, String owner) {


CarModel = model;
CarName = name;
CarPrice = price;
CarOwner = owner;
}

void displayCarData() {
[Link]("Car Model: " + CarModel);
[Link]("Car Name: " + CarName);
[Link]("Car Price: " + CarPrice);
[Link]("Car Owner: " + CarOwner);
[Link]("-------------------------");
}
}
}
package Hamdan1;

import [Link];

public class CarMain {

public static void main(String[] args) {


public class Main {
public static void main(String[] args)
Car myCar = new Car();

[Link]("2022", "Honda Civic", 4500000.00, "Hamdan ");

Dr. M. Bilal Shahnawaz Lab-05 6


2ndSemester Lab-05: Classes, Objects and Methods in Java

}
}}
Output

Dr. M. Bilal Shahnawaz Lab-05 7

Common questions

Powered by AI

Method overloading in the 'Box' class could be utilized by creating multiple 'setDim' methods with different signatures, such as allowing different parameter types (e.g., integers, floats), enabling both individual and bulk assignments of dimensions, or offering additional convenience methods that preset common dimension settings. This provides users flexibility in how they instantiate and manipulate 'Box' objects, catering to varied input requirements and improving ease of use through intuitive API design. Such extensions enhance usability and adapt class capabilities to diverse contexts beyond the default configurations .

Adding methods that return values enhances program functionality by making objects retrieve instead of just exhibit state, thus enabling more complex interactions. For the 'Box' class, a method like 'volume()' returning the volume allows for flexibility in utilizing the computation elsewhere, such as within conditional logic or other computations. It separates data processing and usage, enabling decoupled and modular code where calculations can be independently verified or replaced without affecting how the results are used elsewhere .

The suggested change for managing object initialization in the 'Box' class involves using a method that takes parameters to set dimensions, specifically 'setDim(double w, double h, double d).' This approach significantly simplifies the object initialization process by replacing multiple direct assignments with a single method call. It promotes code maintainability and readability by encapsulating initialization logic, thereby preventing errors and fostering reusability .

A method that modifies class variables directly allows for immediate variable assignment within the main function or any other class accessing public member variables. This is straightforward but restricts validation and constraints on the data being assigned. In contrast, a parameterized method, such as 'setDim(double w, double h, double d)' in the 'Box' class, allows for encapsulating the logic in setting multiple related variables with potential validation checks and reductions in repetitive code. This parameterized approach enhances code robustness, facilitates maintenance, and reinforces encapsulation .

Getter methods provide controlled access to private variables in a class, enforcing encapsulation while allowing external classes to retrieve data. In the 'Rectangle' class, getter methods like 'getLength()' and 'getWidth()' serve this function effectively, enabling other classes to access the current dimensions of a rectangle without directly exposing the internal state. This design pattern enhances data security and object integrity, offering interface-level control over data manipulation .

A potential error in the 'Rectangle' class implementation is incorrectly using 'width = width;' instead of 'width = wid;' inside the 'setDimensions(double len, double wid)' method, which prevents the 'width' from being initialized correctly. This can be resolved by correcting the assignment statement to 'width = wid;' ensuring the 'setDimensions' method properly assigns the width value passed as a parameter .

Encapsulation in the 'addressBook' class is applied by exposing methods that display the object's states (name, address, and phone) through 'showName(),' 'showAddress(),' and 'showPhone()' methods. These methods allow external classes to interact with the 'addressBook' attributes indirectly, without accessing them directly. Though the attributes are public here, encapsulating the interaction logic within methods helps structure code to potentially add more functionality or validation .

In object-oriented programming, methods in a class, such as those in the 'Box' class, serve as functions that define behaviors or actions for the objects created from the class. They facilitate operations on the object's data, like calculating the volume in the 'Box' class. For instance, the 'volume()' method computes the volume by multiplying the 'width,' 'height,' and 'depth' properties. Methods can also return values, as shown in the 'Box' class where a method 'volume()' returns the calculated volume, allowing external classes to use these calculations .

In the 'Rectangle' class, encapsulating data with private access specifiers ensures that 'length' and 'width' can only be accessed and modified within the class itself, protecting the data from unauthorized access and modifications. This enforces data integrity and security, as changes to these attributes must be made through defined interface methods like 'setDimensions,' 'getLength,' and 'getWidth,' allowing control and validation before any modification or retrieval. It exemplifies data encapsulation and abstraction principles in object-oriented programming .

Encapsulation can be demonstrated using a class that calculates the area and perimeter of a rectangle by defining a 'Rectangle' class with private instance variables 'length' and 'width.' The class provides public methods to set these variables, such as 'setDimensions(double len, double wid),' and to return the values via 'getLength()' and 'getWidth()' methods. This allows controlled access to the rectangle's properties, ensuring that length and width are only set and retrieved using these methods. The class further includes methods to calculate perimeter, using 2*L + 2*W, and area, using L*W, which use the encapsulated data .

You might also like