What is Java Modifier?
Java Modifier is a keyword used for changing the behavior of variable or class in term of its usage.Java Modifier is categorized in two parts:-
- Access Modifier
- Non Access Modifier
How can we use a modifier?
Simple usage of modifier:
modifier variableName;
where modifier is a keyword i.e. public, private, protected, static, final etc...
What is Java Access Modifier?
Java Access Modifier is like a security key which gives different access to classes, variables, methods or constructor . In simple word, it controls the access level and it use for security reason.
The four Java Access Modifier are:
- default :-> It gives access to package (no need to write it).
- public :-> Give access to the world.
- private :-> Give access to the class only.
- protected :-> Give access to package and all sub classes.
Example:
//This class can be used by the world.
public class Test{
private int myInt; //this variable only access by class Test.
public String myString; //this variable access by everyone.
protected int count; //this variable can access in class and sub class.
private void myMethod(){
}
}
What is Java Non Access Modifier?
Java Non Access Modifier provide various functionality and they are as follows:
- static :-> this modifier allows direct access to method and variable without creating an object for its class.
- final :-> this modifier affect class, method and variable too in following ways:
- A class cannot be subclassed by using final modifier.
- A method cannot be override with its sub class.
- A variable cannot change its value one initialized.
- abstract :-> it use for creating abstract class or method. It means if a class is abstract then it can't be use as a object. It only work as a parent class and it's subclass must have to complete its abstract methods.
Example:
abstract class A{
......
......
public abstract void myMethod();
}
class B extends A{
......
......@Override public void myMethod(){
.....
.....
}
} - synchronized :->this modifier used in thread, so we can discuss in Thread tutorial.
- volatile :-> this modifier also used in thread.
Some important information:
- We can use 1 Access Modifier with 1 or more Non-Access Modifier for same variable/class/method.
- We cannot use abstract and final same time.
- We cannot use private with abstract.
No comments:
Post a Comment