Search code examples
javagettergetter-setteraccessor

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.


Solution

  • 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?