0

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.

Matt
  • 74,352
  • 26
  • 153
  • 180
VedantK
  • 9,728
  • 7
  • 66
  • 71
  • 2
    Why do you want to return same object ?? Does it make sense ? – Rahman Sep 22 '15 at 07:26
  • 1
    Depends what `studentObject` should be. Right now, it's not very clear what exactly you're asking. – Manu Sep 22 '15 at 07:29
  • Why do you want to do this? Should `getStudent()` return a new object with new or different parameters, simply the same object, or a single instance? Can `getStudent` be static? Also: http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem – Ian2thedv Sep 22 '15 at 07:44

5 Answers5

7

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.

user3437460
  • 17,253
  • 15
  • 58
  • 106
3
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?

Stultuske
  • 9,296
  • 1
  • 25
  • 37
2

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 :).

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
1

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;.

Rahul Yadav
  • 1,503
  • 8
  • 11
1

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);
}
Danyal Sandeelo
  • 12,196
  • 10
  • 47
  • 78