Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android Build an Interactive Story App (Retired) Finishing the User Interface Using a Model in the Controller

Mint Milano
Mint Milano
3,114 Points

I am unable to understand the getter and setter methods. Can anyone explain the use of these methods

Can Anyone give application of these methods using a small example.

LandingActivity.java
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class LandingActivity extends Activity {

    public Button mThrustButton;
    public TextView mTypeLabel;
    public EditText mPassengersField;



    public Spaceship mSpaceship;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_landing);

        mThrustButton = (Button)findViewById(R.id.thrustButton);
        mTypeLabel = (TextView)findViewById(R.id.typeTextView);
        mPassengersField = (EditText)findViewById(R.id.passengersEditText);

        // Add your code here!


         mSpaceship= new Spaceship("FIREFLY"); 



    }
}
Spaceship.java
public class Spaceship {
    private String mType;
    private int mNumPassengers = 0;

    public String getType() {
      return mType;
    }

    public void setType(String type) {
      mType = type;
    }

    public int getNumPassengers() {
      return mNumPassengers;
    }

    public void setNumPassengers(int numPassengers) {
      mNumPassengers = numPassengers;
    }

    public Spaceship() {
      mType = "SHUTTLE";
    }

    public Spaceship(String type) {
      mType = type;
    }
}

1 Answer

Ken Alger
STAFF
Ken Alger
Treehouse Teacher

Kaushik;

That is a great question. Let's look at it from a high language level abstracted a bit away from strictly an Android setting.

getters and setters come out of one of the fundamental Object Oriented Programming (OOP) concepts called encapsulation. Encapsulation is a way of wrapping data (variables) and the coding doing something with that data (methods) together. We encapsulate class variables and hide them from other classes and make them accessible only through methods of the current class.

To achieve encapsulation in Java

  • Declare the variables of a class as private.
  • Provide public setter and getter methods to modify and view the variables values.

That sounds all great and, if you are anything like me, doesnโ€™t really mean much without an example. So, letโ€™s do that.

Employee.java
public class Employee{

   private String name;
   private String idNum;
   private int age;

   public int getAge(){
      return age;
   }

   public String getName(){
      return name;
   }

   public String getIdNum(){
      return idNum;
   }

   public void setAge( int newAge){
      age = newAge;
   }

   public void setName(String newName){
      name = newName;
   }

   public void setIdNum( String newId){
      idNum = newId;
   }
}

Obviously we would store much more about an employee, but this is just a sample. Now, to your question of how do you access and use this โ€œhiddenโ€ data from another class.

RunEmployee.java
public class RunEmployee{

   public static void main(String args[]){
      Employee employee = new Employee();
      employee.setName("James");
      employee.setAge(20);
      employee.setIdNum("12343ms");

      System.out.print("Name: " + employee.getName() +
                       " | Age: " + employee.getAge() +  
                       " | Id: " + employee.getIdNum());
    }
}

If we were to run this we would get the following output:

Name: James | Age: 20 | Id: 12343ms

Some of the benefits of encapsulation include:

  • The fields of a class can be made read-only or write-only.
  • A class can have total control over what is stored in its fields.
  • The users of a class do not know how the class stores its data. A class can change the data type of a field and users of the class do not need to change any of their code.

Does that help at all? Please post back with further questions. Getters and Setters are an important concept in Java, as well as other languages, so getting a good grasp on them is important.

Happy coding,
Ken

Mint Milano
Mint Milano
3,114 Points

Thank You Sir, It has been really helpful for understanding getter and setter methods