0
0
Javaprogramming~10 mins

Data hiding 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 variable in a class.

Java
class Person {
    [1] String name;
}
Drag options to blanks, or click blank then click option'
Apublic
Bprivate
Cprotected
Dstatic
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using public instead of private, which does not hide the data.
Using static which is unrelated to access control.
2fill in blank
medium

Complete the code to provide a public method to access the private variable.

Java
class Person {
    private String name;
    public String [1]() {
        return name;
    }
}
Drag options to blanks, or click blank then click option'
AgetName
Bname
CsetName
DprintName
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using setName which is a setter, not a getter.
Using the variable name directly as method name.
3fill in blank
hard

Fix the error in the setter method to correctly set the private variable.

Java
class Person {
    private String name;
    public void setName(String [1]) {
        name = [1];
    }
}
Drag options to blanks, or click blank then click option'
Athis.name
Bname
CnewName
Dvalue
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 correctly implement a setter method using 'this' keyword.

Java
class Person {
    private int age;
    public void setAge([1] age) {
        [2].age = age;
    }
}
Drag options to blanks, or click blank then click option'
Aint
Bthis
CPerson
Dprivate
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using class name instead of 'this' to refer to the field.
Omitting the parameter type.
5fill in blank
hard

Fill all three blanks to create a class with a private variable and a getter.

Java
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 setter name instead of getter.
Returning a wrong variable name.