Implementing Access Modifiers in Java
Create a class named Person
with the following fields: name
(String), age
(int), and address
(String). The name
field should be public, the age
field should be private, and the address
field should be protected. Also, create a public method display
that prints the name and age of the person in the following format:
Name: <name>
Age: <age>
25
Age: 25
Age: 25
16
Age: 16
Age: 16
18
Age: 18
Age: 18
Instructor solution
Think you've got it?
Which of the following statements about access modifiers in Java is correct?
- A.
The
protected
access modifier restricts access to the class itself,public
allows access from any class, andprivate
allows access within the same package and subclasses. - B.
All access modifiers (
public
,private
,protected
) restrict access to the class itself. - C.
The
public
access modifier restricts access to the class itself,private
allows access from any class, andprotected
allows access within the same package and subclasses. - D.
The
private
access modifier restricts access to the class itself,public
allows access from any class, andprotected
allows access within the same package and subclasses.
You may exit out of this review and return later without penalty.