0
0
Javaprogramming~10 mins

Private data members 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 integer variable named age.

Java
class Person {
    [1] int age;
}
Drag options to blanks, or click blank then click option'
Astatic
Bprivate
Cprotected
Dpublic
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using 'public' instead of 'private' allows access from anywhere.
Using 'static' changes the variable to belong to the class, not an instance.
2fill in blank
medium

Complete the code to create a private String variable called name.

Java
class Student {
    [1] String name;
}
Drag options to blanks, or click blank then click option'
Apublic
Bfinal
Cprivate
Dprotected
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using 'public' exposes the variable to all classes.
Using 'final' makes the variable constant but does not restrict access.
3fill in blank
hard

Fix the error in the code by choosing the correct access modifier for the data member.

Java
class Car {
    [1] String model;
}
Drag options to blanks, or click blank then click option'
Aprivate
Bpublic
Cstatic
Dfinal
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using 'public' exposes the variable to all classes.
Using 'static' or 'final' does not control access.
4fill in blank
hard

Fill both blanks to declare two private data members: an int id and a String name.

Java
class Employee {
    [1] int id;
    [2] String name;
}
Drag options to blanks, or click blank then click option'
Aprivate
Bpublic
Cprotected
Dstatic
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Mixing access modifiers can cause inconsistent access.
Using 'public' exposes the variables.
5fill in blank
hard

Fill all three blanks to declare private data members: a String title, an int pages, and a double price.

Java
class Book {
    [1] String title;
    [2] int pages;
    [3] double price;
}
Drag options to blanks, or click blank then click option'
Apublic
Bprivate
Cprotected
Dfinal
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using 'public' or 'protected' exposes the data members.
Using 'final' only makes variables constant but does not restrict access.