To return an object in Java, you can use the return
statement in a method. The return
statement causes the method to exit and provides a value back to the calling code.
Here is an example of how you can return an object in Java:
class Dog { String name; int age; Dog(String name, int age) { this.name = name; this.age = age; } } class Main { public static void main(String[] args) { Dog dog = getDog(); System.out.println(dog.name + " is " + dog.age + " years old."); } public static Dog getDog() { return new Dog("Buddy", 5); } }
In this example, the Dog
class represents a simple object with a name
and an age
. The getDog
method returns a new Dog
object with the name "Buddy" and the age 5. The returned object is then assigned to the dog
variable in the main
method, and its properties are printed to the console.
Note that the type of the object being returned must be specified in the method signature. In this case, the getDog
method returns an object of type Dog
, so the method is declared as public static Dog getDog()
.