Lorem ipsum dolor sit amet, consectetur adipiscing elit. Test link

getters and setters methods in Android and Java

In Java, getters and setters are methods used to access and modify the values of private instance variables in a class. These methods provide a way to encapsulate the data of an object and enforce control over how the data is accessed and manipulated. In Android, getters and setters are commonly used to access and modify the properties of UI widgets such as TextViews, EditTexts, Buttons, etc.

Here is an example of a class in Java that uses getters and setters to encapsulate its data:

public class Person {
    private String name;
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

In this example, the Person class has two private instance variables name and age. To access and modify these variables, we have provided public getter and setter methods for each variable. The getName() and getAge() methods return the values of name and age, respectively, while the setName() and setAge() methods set the values of name and age, respectively.

Here is an example of how to use the Person class:

Person person = new Person();
person.setName("John");
person.setAge(25);
System.out.println("Name: " + person.getName());
System.out.println("Age: " + person.getAge());

In Android, getters and setters are commonly used to access and modify the properties of UI widgets. Here is an example of a TextView widget in Android that uses getters and setters:

public class MainActivity extends AppCompatActivity {
    private TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView = findViewById(R.id.text_view);
        textView.setText("Hello, world!");
    }

    public void setText(String text) {
        textView.setText(text);
    }

    public String getText() {
        return textView.getText().toString();
    }
}

In this example, the MainActivity class has a private instance variable textView that represents a TextView widget. We have provided public getter and setter methods setText() and getText() that set and get the text of the TextView widget, respectively. We can use these methods to access and modify the text of the TextView widget in our app.

Here is an example of how to use the MainActivity class to set and get the text of the TextView widget:

MainActivity mainActivity = new MainActivity();
mainActivity.setText("Hello, world!");
String text = mainActivity.getText();

Post a Comment