Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to declare a private variable named age of type int.
Java
private [1] age;Attempts:
3 left
💡 Hint
Common Mistakes
Using
String instead of int for age.Forgetting to specify the data type.
✗ Incorrect
The
private keyword restricts access, and int is the correct type for the variable age.2fill in blank
mediumComplete the code to create a private method named getAge that returns an int.
Java
private [1] getAge() { return age; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using
void as return type when the method returns a value.Using
String instead of int.✗ Incorrect
The method
getAge returns an integer, so its return type must be int.3fill in blank
hardFix the error in the code by completing the blank to access the private variable name inside the class.
Java
public String getName() { return this.[1]; }Attempts:
3 left
💡 Hint
Common Mistakes
Using uppercase
Name instead of name.Trying to call
name() as a method.✗ Incorrect
The private variable is named
name with lowercase, so this.name accesses it correctly.4fill in blank
hardFill both blanks to create a private constructor that initializes the private variable id.
Java
private [1]([2] id) { this.id = id; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using
void as constructor return type.Using wrong parameter type like
String.✗ Incorrect
The constructor name must match the class name
MyClass, and the parameter type for id is int.5fill in blank
hardFill all three blanks to create a private setter method named setScore that updates the private variable score.
Java
private [1] setScore([2] score) { this.[3] = score; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using a return type other than
void.Using wrong parameter type like
String.Using incorrect variable name in assignment.
✗ Incorrect
The setter method returns nothing (
void), takes an int parameter named score, and assigns it to the private variable score.