Software Access Modifiers Flashcards
What are Software Access Modifiers (SAMs)
- They are keywords in object oriented languages: C++, Java, Python etc.
- These set the accessibility of classes, methods and other members
What are the 3 access modifiers
- Public
- Protected
- Private
Level Access Modifiers
Top Level - can use public
Member Level - can use public, private and protected
Top Level
- Declared with public access modifiers: Visible to all classes everywhere
- Declared with no access modifier: Visible only to classes within its own package
Member level
no access and public same as Top level
-Class member declared with private access modifier: can only
be accessed by its own class
-
Class member declared with protected access modifier: can only be accessed by classes in its own package and subclasses in another package
Class
Always has access to its own members
Package
Can only access public, protected and package-private (no modifier) members
Subclass
can only access public and protected members
World
can only access public members
How do Access levels affect programming
- Classes coming from another source- the access levels determine which members of those classes your own classes can use
- When writing a class - you need to decide what access level every member variable and every method in your class should have
Why use access modifiers
Security viewpoint - encapsulation stops class members from being changed in an uncontrollable way
Programming viewpoint - changes made to a public class variable could mean changing the code everywhere that uses that variable
Choosing Access Modifiers
- Use the most restrictive access level that makes sense for a particular class member
- Use private unless you have a good reason not too
- Avoid public fields except for constants which cannot be changed
Immutable objects
- It is an object whose internal state remains constant after it has been created.