ICS102 - Lab8 - Defining Classes
ICS102 - Lab8 - Defining Classes
Objectives:
By completing this lab, students should be able to:
Static variables and methods.
The Math class.
Syntax Reference with examples:
Following are the syntaxes for the required commands.
Syntax:
Syntax:
Exercise
All of1:its methods and data are static; therefore, they are invoked with the
class name Math instead of a calling object
Correct the following java code. Highlight the errors and identify the reasons. Try to solve it on
paper before using JCreator.
Exercise 1 :
Correct the following java code . highlight the errors and identify the reasons
import java.util.Math;
class MathTest {
public static void main(String[] args) {
obj.abs(-9);
System.out.println(math.floor(6.9));
number = math.max(-3, -7);
System.out.println(number);
number= obj.sqrt(16);
}
}
Exercise 2:
1. Create a new Java file named exercise2 and add it to the lab 8 project.
2. Define a class named Sphere that contains:
a. A double variable named radius.
b. A String variable named name.
c. A default constructor to initialize the radius and name to 0.
d. A parameterized constructors to initialize the radius and the name of the sphere.
e. Mutator methods for the radius and name.
f. Accessor methods for the radius and name.
g. A method named sphereVolume with no parameters to compute and then return the volume
3
of the sphere according to the formula 𝑉𝑜𝑙𝑢𝑚𝑒 = 𝜋𝑟 3
4
- In this Java class named Sphere, the specified requirements are fulfilled:
1. It contains a double variable radius and a String variable name
2. It has a default constructor that initializes radius and name to 0 and "NoName" respectively.
3. It has a parameterized constructor that allows initialization of radius and name.
4. It includes mutator methods setRadius(double radius) and setName(String name) to modify the
values of radius and name respectively.
5. It provides accessor methods getRadius() and getName() to retrieve the values of radius and
name
6. It has a method sphereVolume() that computes and returns the volume of the sphere based on
the given formula Volume = (3/4) * π * r^3
1. It instantiates the Sphere class with an object named s1 using the default constructor.
2. It calls the appropriate mutator methods setRadius(double radius) and setName(String name) to set
the values of radius and name for s1 with 3.1 and "sphere1" respectively
3. It calculates and displays the volume of the sphere s1 using the sphereVolume() method.
4. It displays the information of sphere s1 by retrieving the radius and name using accessor methods
getRadius() and getName()