An access modifier is a keyword that change the meaning of a definition. There are two kinds: access modifiers and non-access modifiers.
Access modifiers:
Public: can be accessed from any other scope.
Can be applied to classes, methods, constructors, instance variables, interfaces and interfaces members (default).
Private: can be accessed only from the same class.
Can be applied to methods, isntance variables, constructors and inner classes.
Cannot be applied to classes, local variables and interface members.
Protected: can be accessed by any subclass or any class within the same package.
Can be applied to methods, isntance variables, constructors and inner classes.
Cannot be applied to classes, local variables and interface members.
Default Access Modifier: can be accessed only from within the same package.
When no access modifiers is specified, it's the default behaviour for classes, inner classes, member variables and constructors.
But it's not the default behaviour for interfaces, where all methods are abstract, public, and where all member variables are public, static and final.
Note that overridden methods can only be made more public, not more private.
Non-access modifiers:
Final
A final class cannot be subclassed
A final method can't be overridden
A final variable can only be initialized once, via initializer or assignment. Also a parameter can be final.
Note that all the methods of a final class are final.
Note that a final object means the reference cannot be changed, but the state of the object can still be changed.
Abstract
An abstract class cannot be instantiated.
An abstract class doesn't necessarily has abstract methods.
If a class has at least an abstract method, whether declared or inherited, the entire class must be declared abstract
A member variable cannot be abstract.
An abstract class can extend an other abstract class or concrete class, or implement an interface.
A concrete class must implement all the abstract methods that inherits.
Static
It's a variable or method that belongs to the class and not to the instance.
A static block is a block inside a Java class that will be executed when a class is first loaded.
A static method can only access static methods and static member variables.
Polymorphism is not possible with static methods.
There are other less common modifiers like transient (for serialization), volatile and synchronized (used for threads).
Copyright © 2013 Welcome to the website of Davis Fiore. All Rights Reserved.