Reputation: 10112
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.
Upvotes: 0
Views: 10920
Reputation: 1513
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;
.
Upvotes: 1
Reputation: 17454
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.
Upvotes: 7
Reputation: 12391
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);
}
Upvotes: 1
Reputation: 122018
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 :).
Upvotes: 2
Reputation: 9437
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?
Upvotes: 3