Access Control and Misc Terms
Access Control
- Fields and methods can have any of the following access level. Classes can only have public and default access.
Modifier | Same Class | Same Package | Subclass | Universe |
public | Yes | Yes | Yes | Yes |
protected | Yes | Yes | Yes | |
default
(no specified access mode) | Yes | Yes | | |
private | Yes | | | |
Binding
- The term binding refers to when the use of a variable, class, or method is resolved.
- Dynamic binding means that the reference is resolved at runtime.
- Static binding means that the reference is resolved at compile-time.
- Keep an eye out for examples of dynamic binding in Java.
- The term virtual method call refers to the way that polymorphism works in java - when a method is called, it is "virtual" because it is dynamically bound at runtime based on the class of the object being used.
- Static binding is more efficient because the compiler binds the call at compile-time.
Final
- The keyword final indicates that the identifier is in some sense constant.
- You cannot subclass a final class
- You cannot override a final method
- Methods declared as final are sometimes used for optimization, since virtual method invocation will not be used.
- Methods marked as static or private are automatically final because dynamic binding cannot be applied in either case.
- A final variable is a constant
- If you mark a reference as final, that reference cannot refer to any other object. (But you can still change the contents of the object)
- You can set a final variable only once, but that assignment can occur independently of the declaration; this is called "blank final variable"
- The last opportunity to set a blank final instance field is in the constructor
- A blank final local variable (i.e. declared in a method) must be set in the method body before being used
Static Block
- A class can contain code in a static block that does not exist within a method body
- Static block code executes only once, when the class is loaded
- A static block is usually used to initialize static (class) attributes
- Different static blocks within a class are executed in the order of their appearance in the class.
Constructor Invocation
Memory is allocated and initialized when a constructor is called. Instance variable initialization uses these steps recursively:
- Bind constructor parameters.
- If explicit this(), call recursively, and then skip to step 5.
- Call recursively the implicit or explicit super call, except for Object.
- Execute the explicit instance variable initializers.
- Execute the body of the current constructor.