Java
In this tutorial we will learn how to return object of a class from a method in Java programming language.
In the previous tutorial we learned how to pass an object as argument to a method.
Now, lets go ahead and create a class that will return an object.
In the following example we have Cube
class and it returns an object when we make a call to its method.
class Cube {
// variable
private double side;
private double volume;
// constructor
Cube(double side) {
this.side = side;
}
// method
public Cube getObject() {
Cube obj = new Cube(this.side);
this.volume = this.side * this.side * this.side;
obj.volume = this.volume;
return obj;
}
public double getVolume() {
return this.volume;
}
public double getSide() {
return this.side;
}
}
public class ReturnObjectExample {
public static void main(String[] args) {
// create first object
Cube obj1 = new Cube(10);
// now create second object using the first object
Cube obj2 = obj1.getObject();
// output
System.out.println("Object #1");
System.out.println("Side: " + obj1.getSide());
System.out.println("Volume: " + obj1.getVolume());
System.out.println("Object #2");
System.out.println("Side: " + obj2.getSide());
System.out.println("Volume: " + obj2.getVolume());
}
}
Output:
$ javac ReturnObjectExample.java
$ java ReturnObjectExample
Object #1
Side: 10.0
Volume: 1000.0
Object #2
Side: 10.0
Volume: 1000.0
So, in the above example we have the Cube class and we are setting the side of the cube via the constructor.
Now, inside the ReturnObjectExample class we are creating the first object obj1
of the Cube class and passing the side 10 so, the side is initialised via the constructor.
Next, we create another Cube variable obj2
and call the getObject()
method of obj1
which returns an object of the Cube class.
Then we are printing out the values of the objects.
When we are writing the following code Cube obj2 = obj1.getObject();
in the above example, the called method getObject()
of obj1
object is returning the reference of the newly created object.
So, obj2
is getting the reference of the newly created object.
ADVERTISEMENT