Java Module 2 Chapter 6
Java Module 2 Chapter 6
type methodName1(parameter-list) {
// body of method
}
…
type methodNameN(parameter-list) {
// body of method
}
}
A class & its associated test class
class Box {
double width;
double height;
double depth;
}
public class BoxTest {
public static void main(String args[]) {
double volume() {
return width * height * depth;
}
}
Lab Activity/Exercise 14
Use the new (or second) version of the Box Class.
Write the new version of the BoxTest class, create a
couple of objects, and use the volume() method in the
print statements to display the volume of each object.
Method Return Type
• The type of data returned by a method must be compatible with
the return type specified by the method. For example, if the return
type of some method is boolean, you should not return an integer.
• The variable receiving the value returned by a method (volume,
in the above case) must also be compatible with the return type
specified for the method.
● Effectively we can write System.out.println("Volume is " +
box1.volume());
Parameterized Methods – Always better
int square() {
return 10 * 10;
}
can be generalized as
int square(int i) {
return i * i;
}
Parameter and argument
square(int i) { // i - parameter in the method definition
}
● square(100) // 100 - argument when you call/invoke
What is wrong with this code?
box1.width = 10;
box1.height = 20;
box1.depth = 15;
Box() {
System.out.println("Constructing Box");
width = 10;
height = 10;
depth = 10;
}
double volume() {
return width * height * depth;
}
}
class BoxTest {
public static void main(String args[]) {
Box box1 = new Box();
Box box2 = new Box();
double volume;
volume = box1.volume();
System.out.println("Volume is " + volume);
volume = box2.volume();
System.out.println("Volume is " + volume);
}
}
Parameterized Constructors
class Box {
double width;
double height;
double depth;
double volume() {
return width * height * depth;
}
}
class BoxTest {
public static void main(String args[]) {
Box box1 = new Box(10, 20, 15);
Box box2 = new Box(3, 6, 9);
double volume;
volume = box1.volume();
System.out.println("Volume is " + volume);
volume = box2.volume();
System.out.println("Volume is " + volume);
}
}
● Box box1 = new Box(10, 20, 15);
●the values 10, 20, and 15 are passed to the Box()
constructor when new creates the object.
●Thus, box1’s copy of width, height, and depth will
contain the values 10, 20, and 15 respectively.
The this Keyword
● this is a keyword.
● Used in any method to refer to the current object.
● It is a reference to an object on which the method is invoked.
● Solves the ambiguity between instance variable and parameter
●Suppose the instance variable and parameter have different
names, then no need of this keyword.
class Student {
int rollNumber;
String name;
float fee;