0
0
Javaprogramming~10 mins

Encapsulation best practices in Java - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to declare a private field in a class.

Java
public class Person {
    private String [1];
}
Drag options to blanks, or click blank then click option'
Apublic
BgetName
CPerson
Dname
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using public instead of private for fields.
Using method names instead of field names.
2fill in blank
medium

Complete the code to create a public getter method for the private field.

Java
public class Person {
    private String name;

    public String [1]() {
        return name;
    }
}
Drag options to blanks, or click blank then click option'
AgetName
BName
CsetName
Dname
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Naming the getter method incorrectly.
Using the field name directly as method name.
3fill in blank
hard

Fix the error in the setter method to properly set the private field.

Java
public class Person {
    private String name;

    public void setName(String [1]) {
        name = [1];
    }
}
Drag options to blanks, or click blank then click option'
AnewName
Bthis.name
Cname
DName
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using the same name for parameter and field without this keyword.
Not assigning the parameter value to the field.
4fill in blank
hard

Fill both blanks to complete the setter method using the this keyword.

Java
public class Person {
    private String name;

    public void setName(String [1]) {
        [2].name = name;
    }
}
Drag options to blanks, or click blank then click option'
Aname
BnewName
Cthis
DPerson
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Not using this when parameter and field names are the same.
Using class name instead of this.
5fill in blank
hard

Fill all three blanks to create a class with a private field and a getter following encapsulation best practices.

Java
public class Car {
    private String [1];

    public String [2]() {
        return [3];
    }
}
Drag options to blanks, or click blank then click option'
Amodel
BgetModel
DsetModel
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using public fields instead of private.
Getter method not returning the correct field.