Page 371 - Computer_Science_F5
P. 371
Computer Science hiding within classes. Below is an in-depth package and subclasses, regardless of the
explanation of the frequently employed package they belong to. The following is
access modifiers.
a syntax for protected access modifier:
public class MyClass {
(a) Public:
FOR ONLINE READING ONLY
The public access modifier grants
unrestricted access to a class member protected int classAttribute;
}
from any class, regardless of the package
it belongs to. The following is a syntax The “protected” access modifier is
for public access modifier: utilised for class members that require
access within the same package or by
public class MyClass {
subclasses. It allows for controlled
public int classAttributes; sharing of data among interconnected
} classes.
The access modifier “public” is used for
class members that need to be accessed Generally, access modifiers play a
from external classes or packages. crucial role in upholding encapsulation
principles in Java classes. They serve
(b) Private: to prevent unauthorised access to class
The private access modifier limits access members and facilitate data hiding,
to a class member exclusively within its thereby improving the security and
own class. It hides the implementation maintainability of the codebase.
details of the class and guarantees the
integrity of the data. The following is a (d) This keyword
syntax for private access modifier
“This” keyword is used depending on
public class MyClass { various situations. The following are
private int classAttributes; some situations where the keyword is
} used:
The access modifier “private” is used for (i) Used in ambiguous variable name
class members that are not supposed to be In Java, it is not permissible to declare
accessed directly from outside the class. two or more variables with identical
They should be accessed through getter names within a scope, be it class scope
and setter methods for controlled access. or method scope. However, instance
variables and parameters can share the
(c) Protected: same name. The following is a piece of
The protected access modifier provides Java code showing ambiguous variable
access to a class member within its own
names.
362
for Advanced Secondary Schools
Computer Science Form 5.indd 362 23/07/2024 12:34

