Returning class objects in java

Returning objects in Java with an example

Similar to returning primitive types, Java methods can also return objects. A reference to the object is returned when an object is returned from a method, and the calling method can use that reference to access the object.

You can use the following general form to return an object in the Java programming language:

public class ClassName < // Fields or attributes private int attribute1; private String attribute2; // Constructor public ClassName(int attribute1, String attribute2) < this.attribute1 = attribute1; this.attribute2 = attribute2; >// Method that returns an object of the same class public ClassName methodName() < int newVariable1 = attribute1 + 10; String newVariable2 = attribute2.toUpperCase(); // Return an object of the same class return new ClassName(newVariable1, newVariable2); > >

The class ClassName has a constructor that takes two parameters and two attributes, labeled attribute1 and attribute2. Another method in the class, methodName, returns an object of the same class, ClassName.

In the methodName method, two new variables newVariable1 and newVariable2 are created by performing some operations on the attributes attribute1 and attribute2. Then, a new object of the same class ClassName is created using these new variables as arguments to the constructor, and that new object is returned using the «return» keyword.

Читайте также:  Java persistence api перевод

Java returning an object example

The following Java program illustrates the concept of returning an object from a method:

public class ObjectAsReturnValueExample < private int attribute1; private String attribute2; public ObjectAsReturnValueExample(int attribute1, String attribute2) < this.attribute1 = attribute1; this.attribute2 = attribute2; >public ObjectAsReturnValueExample modifyObject() < int newVariable1 = attribute1 + 10; String newVariable2 = attribute2.toUpperCase(); return new ObjectAsReturnValueExample(newVariable1, newVariable2); >public static void main(String[] args) < ObjectAsReturnValueExample obj1 = new ObjectAsReturnValueExample(5, "codescracker"); ObjectAsReturnValueExample obj2 = obj1.modifyObject(); System.out.println("Object 1: attribute1 = " + obj1.attribute1 + ", attribute2 = " + obj1.attribute2); System.out.println("Object 2: attribute1 = " + obj2.attribute1 + ", attribute2 obh">Output
Object 1: attribute1 = 5, attribute2 = codescracker Object 2: attribute1 = 15, attribute2 = CODESCRACKER

This program defines a class ObjectAsReturnValueExample with two private attributes attribute1 and attribute2. The constructor of the class initializes these attributes with the passed arguments. The class also includes a modifyObject() method that produces an object that belongs to the same class. A new object is created with the modified values after the attribute1 and attribute2 values of the current object are modified inside the method. The modified values of attribute1 and attribute2 are, respectively, increased by 10 and made uppercase.

Two objects of the ObjectAsReturnValueExample class are created in the main() method. The first object is created with attribute1 and attribute2 initial values of 5 and "codescracker," respectively. The second object is created by calling the first object's modifyObject() method. The modified object is thus returned and assigned to the second object.

Finally, the main() method prints the values of attribute1 and attribute2 for both objects. We can observe that the values of attribute1 and attribute2 of the first object remain unchanged while the second object has modified values. This demonstrates the concept of "object as return value".

Liked this article? Share it!

Источник

Returning a Value from a Method

You declare a method's return type in its method declaration. Within the body of the method, you use the return statement to return the value.

Any method declared void doesn't return a value. It does not need to contain a return statement, but it may do so. In such a case, a return statement can be used to branch out of a control flow block and exit the method and is simply used like this:

If you try to return a value from a method that is declared void , you will get a compiler error.

Any method that is not declared void must contain a return statement with a corresponding return value, like this:

The data type of the return value must match the method's declared return type; you can't return an integer value from a method declared to return a boolean.

The getArea() method in the Rectangle Rectangle class that was discussed in the sections on objects returns an integer:

// a method for computing the area of the rectangle public int getArea()

This method returns the integer that the expression width*height evaluates to.

The getArea method returns a primitive type. A method can also return a reference type. For example, in a program to manipulate Bicycle objects, we might have a method like this:

public Bicycle seeWhosFastest(Bicycle myBike, Bicycle yourBike, Environment env) < Bicycle fastest; // code to calculate which bike is // faster, given each bike's gear // and cadence and given the // environment (terrain and wind) return fastest; >

Returning a Class or Interface

If this section confuses you, skip it and return to it after you have finished the lesson on interfaces and inheritance.

When a method uses a class name as its return type, such as whosFastest does, the class of the type of the returned object must be either a subclass of, or the exact class of, the return type. Suppose that you have a class hierarchy in which ImaginaryNumber is a subclass of java.lang.Number , which is in turn a subclass of Object , as illustrated in the following figure .

The class hierarchy for ImaginaryNumber

Now suppose that you have a method declared to return a Number :

public Number returnANumber()

The returnANumber method can return an ImaginaryNumber but not an Object . ImaginaryNumber is a Number because it's a subclass of Number . However, an Object is not necessarily a Number — it could be a String or another type.

You can override a method and define it to return a subclass of the original method, like this:

public ImaginaryNumber returnANumber()

This technique, called covariant return type, means that the return type is allowed to vary in the same direction as the subclass.

Note: You also can use interface names as return types. In this case, the object returned must implement the specified interface.

Источник

Passing and Returning Objects in Java

Although Java is strictly passed by value, the precise effect differs between whether a primitive type or a reference type is passed. When we pass a primitive type to a method, it is passed by value. But when we pass an object to a method, the situation changes dramatically, because objects are passed by what is effectively call-by-reference. Java does this interesting thing that’s sort of a hybrid between pass-by-value and pass-by-reference.
Basically, a parameter cannot be changed by the function, but the function can ask the parameter to change itself via calling some method within it.

  • While creating a variable of a class type, we only create a reference to an object. Thus, when we pass this reference to a method, the parameter that receives it will refer to the same object as that referred to by the argument.
  • This effectively means that objects act as if they are passed to methods by use of call-by-reference.
  • Changes to the object inside the method do reflect the object used as an argument.

Illustration: Let us suppose three objects ‘ob1’ , ‘ob2’ and ‘ob3’ are created:

ObjectPassDemo ob1 = new ObjectPassDemo(100, 22); ObjectPassDemo ob2 = new ObjectPassDemo(100, 22); ObjectPassDemo ob3 = new ObjectPassDemo(-1, -1);

Passing Objects as Parameters and Returning Objects

From the method side, a reference of type Foo with a name a is declared and it’s initially assigned to null.

boolean equalTo(ObjectPassDemo o);

Passing Objects as Parameters and Returning Objects

As we call the method equalTo, the reference ‘o’ will be assigned to the object which is passed as an argument, i.e. ‘o’ will refer to ‘ob2’ as the following statement execute.

System.out.println("ob1 == ob2: " + ob1.equalTo(ob2));

Passing Objects as Parameters and Returning Objects

Now as we can see, equalTo method is called on ‘ob1’ , and ‘o’ is referring to ‘ob2’. Since values of ‘a’ and ‘b’ are same for both the references, so if(condition) is true, so boolean true will be return.

Again ‘o’ will reassign to ‘ob3’ as the following statement execute.

System.out.println("ob1 == ob3: " + ob1.equalTo(ob3));

Passing Objects as Parameters and Returning Objects

  • Now as we can see, the equalTo method is called on ‘ob1’ , and ‘o’ is referring to ‘ob3’. Since values of ‘a’ and ‘b’ are not the same for both the references, so if(condition) is false, so else block will execute, and false will be returned.

In Java we can pass objects to methods as one can perceive from the below program as follows:

Источник

Tutorial: How to Return Object from a Method in JAVA

Return Object Method JAVA

This developer guide tells how to Return Object from a Method in JAVA using Java Object Methods. First, we will discuss the return type of any method. Then we will see the control flow from invoking code to invoked code and again when control goes back to invoking code. After learning about method overloading and constructor overloading in Java, the content of Java object methods will be easier.

How to Return Object from a Method in JAVA

A method returns to the code that invoked it when it:

  1. Completes all the statements in the method
  2. Reaches a return statement
  3. or Throws an exception (covered later)

Whichever occurs first between the last two. Make sure to declare a method’s return type in its method declaration. You can use the return statement to return the value within the body of the method.

Any method declared void doesn’t return a value. Meanwhile, it does not require to contain a return statement, but if you wish to put you can. In such a case, a return statement can be used to branch out of a control flow block and exit the method and is simply used like this:

If you try to return a value from a method that is declared void, you will get a compiler error.

Any method that is not declared void must contain a return statement with a corresponding return value, like this:

So far it was a recapitulation that we know earlier.

How to return object after a method call in Java

Now we will learn how to return an object after a method call. It seems to be strange. But it’s true that A method can return any type of data, including class types that you create. We will understand how it happens with the following example given below.

Program

class Employee < double salary; Employee(double salary)< this.salary = salary; >Employee updateSalary(double salary) < Employee employee = new Employee(this.salary+salary); return employee; >double getSalary() < return this.salary; >> class ReturnObjectDemo < public static void main(String args[])< Employee kallis = new Employee(34029.48); Employee ronaldo; ronaldo=kallis.updateSalary(6295.28); System.out.println("Salary of Kallis is: "+kallis.getSalary()); System.out.println("Salary of Ronaldo is: "+ronaldo.getSalary()); >>

Output

Return Object Method JAVA

Explanation of the Java Code & Output

As you can see, each time updateSalary( ) is invoked, a new object is created, and a reference to it is returned to the calling routine.

The preceding program makes another important point: Since all objects are dynamically allocated using new, you don’t need to worry about an object going out-of-scope because the method in which it was created terminates.

The object will continue to exist as long as there is a reference to it somewhere in your program. When there are no references to it, the object will be reclaimed the next time garbage collection takes place.

Here object ronaldo of class type Employee is created when updateSalary() is being invoked by the object kallis of Employee class. But the point that is to be noticed that is even though ronaldo is created from object kallis but both will have separate copies of instance variables.

If you are looking for help with java programming homework, Check out more useful tutorials and definitive guidelines on Java programming here.

Источник

Оцените статью