0% found this document useful (0 votes)
11 views9 pages

Understanding Java Access Modifiers

The document discusses access modifiers in Java, detailing four types: public, private, protected, and default. It explains their visibility and accessibility rules, emphasizing that public members are accessible from any class, private members are restricted to the enclosing class, protected members are accessible to subclasses and classes in the same package, and default members are package-private. Additionally, it includes an exercise to rewrite code using different access modifiers for a variable called account_balance.

Uploaded by

Zooz 24
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views9 pages

Understanding Java Access Modifiers

The document discusses access modifiers in Java, detailing four types: public, private, protected, and default. It explains their visibility and accessibility rules, emphasizing that public members are accessible from any class, private members are restricted to the enclosing class, protected members are accessible to subclasses and classes in the same package, and default members are package-private. Additionally, it includes an exercise to rewrite code using different access modifiers for a variable called account_balance.

Uploaded by

Zooz 24
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Computer programming 2

Lab 6

Access Modifiers

1
1. Access modifiers

1. public: are visible to any class in the Java program,


whether these classes are in the same package or in
another package.

2. private: they cannot be accesses by anywhere


outside the enclosing class.

* A class can not be declared as private

* A standard design strategy is to make all variables private,


and methods public.
2
1. Access modifiers

3. protected:Variables and methods declared


protected in a super class can be accessed only by
subclasses in other packages. Classes in the same
package can also access protected variables, and
methods as well, even if they are not a subclass of the
protected member’s class.

4. default: when no access modifier is present, any class,


variable, and method that has no declared access
modifier is accessible only by classes in the same
package (known as package private).
3
1. Access modifiers

4
5
Example

6
Example

7
Example

8
Question:

- re-write the previous code four times using different access


modifiers for the variable account_balance then run the code
and print screen the result.

You might also like