8.2 Passing objects as arguments to Methods
Object references can be parameters. Call by value is used, but now the value is an object reference. This reference can be used to access the object and possibly change it. Here is an example program:
Program (Rectangle.java)
public class Rectangle
{
private double length;
private double width;
public Rectangle()
{
length = 0.0;
width = 0.0;
}
public Rectangle(double l, double w)
{
length = l;
width = w;
}
public void setLength(double l)
{
length = l;
}
public void setWidth(double w)
{
width = w;
}
public void set(double l, double w)
{
length = l;
width = w;
}
public double getLength()
{
return length;
}
public double getWidth()
{
return width;
}
public double getArea()
{
return length * width;
}
public double getPerimeter()
{
return 2 * (length + width);
}
}
Program (PassObjectDemo.java)
/**
* This program passes an object as an argument.
* The object is modified by the receiving method.
*/
public class PassObjectDemo
{
public static void main(String[] args)
{
// Create an Rectangle object.
Rectangle rect = new Rectangle(10, 20);
// Display the object's contents.
System.out.println("Length : " + rect.getLength());
System.out.println("Width: " + rect.getWidth());
System.out.println("Area: " + rect.getArea());
// Pass the object to the ChangeRectangle method.
changeRectangle(rect);
// Display the object's contents again.
System.out.println();
System.out.println("Length : " + rect.getLength());
System.out.println("Width: " + rect.getWidth());
System.out.println("Area: " + rect.getArea());
}
/**
* The following method accepts an Rectangle
* object as an argument and changes its contents.
*/
public static void changeRectangle(Rectangle r)
{
r.set(30, 5);
}
}
Output :
Length : 10.0
Width: 20.0
Area: 200.0
Width: 20.0
Area: 200.0
Length : 30.0
Width: 5.0
Area: 150.0
Width: 5.0
Area: 150.0
No comments:
Post a Comment