[post-views]
In this lesson, you will learn
This can be particularly useful when you need to compare, modify, or compute based on the properties of objects.
package ch7.l9;
//Objects may be passed to methods.
class MyTest
{
int a, b;
MyTest(int i, int j)
{
a = i;
b = j;
}
// return true if obj is equal to the invoking object
boolean equalTo(MyTest obj)
{
if(obj.a == a && obj.b == b) {
return true;
}
else
return false;
}
}
public class PassingObjToMethod {
public static void main(String[] args) {
MyTest ob1 = new MyTest(10, 11);
MyTest ob2 = new MyTest(10, 11);
MyTest ob3 = new MyTest(-1, -1);
System.out.println("ob1 == ob2: " + ob1.equalTo(ob2));
System.out.println("ob1 == ob3: " + ob1.equalTo(ob3));
}
}
Output
ob1 == ob2: true
ob1 == ob3: false
package ch7.l9;
class Rectangle {
double length;
double breadth;
// Constructor to initialize the dimensions of the rectangle
public Rectangle(double length, double breadth) {
this.length = length;
this.breadth = breadth;
}
// Method to calculate the area of the rectangle
public double calculateArea() {
return length * breadth;
}
}
public class PassingObject {
// Method to compare the areas of two rectangles
public void compareArea(Rectangle rect1, Rectangle rect2) {
double area1 = rect1.calculateArea();
double area2 = rect2.calculateArea();
if (area1 > area2) {
System.out.println("Rectangle 1 is larger with an area of " + area1);
} else if (area2 > area1) {
System.out.println("Rectangle 2 is larger with an area of " + area2);
} else {
System.out.println("Both rectangles have the same area of " + area1);
}
}
// Main method to run a simple test
public static void main(String[] args) {
// Creating two rectangle objects
Rectangle rectangle1 = new Rectangle(5.0, 2.0);
Rectangle rectangle2 = new Rectangle(3.0, 4.0);
// Creating an instance of RectangleOperations
PassingObject po = new PassingObject();
// Comparing the areas of the two rectangles
po.compareArea(rectangle1, rectangle2);
}
}
Output
Rectangle 2 is larger with an area of 12.0
There are no reviews yet. Be the first one to write one.
You must be logged in to submit a review.