Complete the code to declare a private variable in a class.
class Person { [1] String name; }
The keyword private hides the variable from outside the class, enabling data hiding.
Complete the code to provide a public method to access the private variable.
class Person { private String name; public String [1]() { return name; } }
The method to access a private variable is called a getter, usually named starting with 'get'.
Fix the error in the setter method to correctly set the private variable.
class Person { private String name; public void setName(String [1]) { name = [1]; } }
The parameter name should be different from the field name to avoid confusion. Using newName allows setting name = newName;.
Fill both blanks to correctly implement a setter method using 'this' keyword.
class Person { private int age; public void setAge([1] age) { [2].age = age; } }
The setter method takes an int parameter and uses this to refer to the current object's field.
Fill all three blanks to create a class with a private variable and a getter.
class Car { private String [1]; public String [2]() { return [3]; } }
The private variable is model. The getter method is getModel and it returns the variable model.