Modifiers-

Definition- These are the keywords which  modifies properties of classes and fields.

Types of modifiers-

1- Access modifiers
2-Non-access modifiers

modifiers-in-java

1-Access modifier- Modifies accessibility of   classes and fields.

-Controls visibility.

(i)Private    -only within class

(ii)Default   – only within package.

(iii)Protected  -within package and outside the package using inheritance

(iv)Public        – everywhere

accesscontrol

Note- classes can’t be private and protected.
Note- Local variables can’t have any access modifier

java-tutorial-47-638

code samples are here

1- Program to demonstrate access modifiers on variables

axs

i- Program for class ExUsingVar


package AccessModifiers8;
public class ExUsingVar {
public int a=10;
private int b=20;
protected int c=30;
int d=40; 

public static void main(String[] args) {
ExUsingVar e1 =new ExUsingVar();
System.out.println(e1.a);
System.out.println(e1.b);
System.out.println(e1.c);
System.out.println(e1.d);
}
}

 

ii-Program for class ExUsingVar1

  

package AccessModifiers8;
<pre>public class ExUsingVar1 {

public static void main(String[] args) {
ExUsingVar e1 =new ExUsingVar();
System.out.println(e1.a);
System.out.println(e1.b);
System.out.println(e1.c);
System.out.println(e1.d);
}
}

iii-Program to show ExUsingVar3


package AccessModifiers8_1;
<pre>import AccessModifiers8.ExUsingVar;

public class ExUsingVar3 {

public static void main(String[] args) {
ExUsingVar e1 =new ExUsingVar();
System.out.println(e1.a);
 System.out.println(e1.b);
 System.out.println(e1.c);
 System.out.println(e1.d);
}

}

 

2-Non Access Modifiers-  (Final,Static,abstract,Transient,Synchronized,Volatile)

1-Final- used to restrict the user.

(a)final variable  -can’t change the value

fnlv

(b) final method – can’t override

fnlv

(c) final class– can’t inherit

fnlv

2-Static-
-static belongs to class rather than objects.
(a) static variable
-gets memory only once in at the time of class loading.
-used to refer the common property of all objects

(b) static method
– can be invoked without an instance/object
-can access static variable

(c) static nested Class
-can access static data members of outer class

-object is create in scope of outer class

(d) static block
– executes even before main method
-used to initialize static data members

java-static-keyword-1

3- Abstract –
-Used in abstraction(oop concept)
-can be applied on-
a- Abstract class
b- Abstract method

4-Transient-
– prevents serialization of value.(Io package concept)
-only for variable

5-Synchronized-(multithreading concept)
-prevents sharing by more than one threads at a time
– can be
a- synchronized method
b- synchronized block

6-Volatile-(multithreading concept)
– Allows modification at runtime unexpectedly.
– only for variable

java-tutorial-47-638-copy

Advertisements