简体   繁体   中英

How to Return Object through getter method in Java

I have always returned single field with getter methods, I was wondering if we can return Object using getter.

I have,

class Student
{
 int age
 String name

 public Student(int age,String name)
{
this.age=age;
this.name=name;
}


public Student getStudent()
{

  // **how can I do this**
return studentObject;
}

I have used ,

public int getAge()
{
return age;
}

many times I need to know how to do with Object Or even we can do it or not.

If you want to return the object itself , do this:

public Student getStudent(){
    return this;
}

If you want to return another instance of the Student object with similar content (a copy of current Student):

public Student getStudent(){
    return new Student(age, name);  //Create a new Student based on current properties
}

Benefit of the 2nd approach: Changes to the new Student object will not affect the original one.

public Student getStudent(){
  return this;
}

But I do hope you understand that this makes no sense at all. In order to be able to return the 'this' of that instance, you would already need the instance to be able to call the method getStudent()

Or do you mean you want to return a cloned object?

Why not ? It's just like any other field. If you have declared a type of Object just return that, or if you just want to return current object do

public Student getStudent()
{
return this;
}

But this doens't make sense, since you need to have an instance to invoke which already the same :).

You can do it in following way if you always want new object

public Student getStudent()
{
   Student studentObject = new Student(10, "ABC");
   return studentObject;
}

else if you want the same object you can return this; .

I assume, you need a new object having the same content as the calling class:

public Student getStudent(){
  return new Student(this.age,this.name);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM