Modifiers are Java keywords that provide information to compiler about the nature of the code, data and classes.- Modifiers are used to control access to data. methods and classes
- If no access modifier is specified, then the accessibility is default package visibilityNOTE:1. Private access specifier is also known as native access specifier.2. Default access specifier is also known as package access specifier.3. Protected access specifier is also known as inherited access specifier.4. Public access specifier is also known as universal access specifier.
CLASSIFICATION OF MODIFIERS
1. Access control modifier : Default, Public, Protected,Private
2.Non Access Modifier
Non-access modifiers do not change the accessibility of variables and methods, but they do provide them special properties. Non-access modifiers are of 5 types,
Final, Static, Transient, Synchronized , Volatile
class Item
{
final int MAX_PRICE = 1999; //final variable
final int MIN_PRICE = 1699;
final void display() //final method
{
System.out.println("Maxprice is" + MAX_PRICE );
System.out.println("Minprice is" + MIN_PRICE);
}
}
{
final int MAX_PRICE = 1999; //final variable
final int MIN_PRICE = 1699;
final void display() //final method
{
System.out.println("Maxprice is" + MAX_PRICE );
System.out.println("Minprice is" + MIN_PRICE);
}
}
String class in java.lang package is a example of final class
Static
- Static Modifiers are used to create class variable and class methods which can be accessed without instance of a class
- Static variable has only one single storage
- Static variables are initialized only once
static variable
class Employee
{
int eno;
String name;
static String company_name ="ABC";
public void show()
{
System.out.println(eno+" "+name+" "+company_name);
}
public static void main( String[] args )
{
Employee e = new Employee();
e.eid = 1;
e.name = "aaa";
e.show();
Employee e2 = new Employee();
e2.eid = 2;
e2.name = “bbb";
e2.show();
}
}
{
int eno;
String name;
static String company_name ="ABC";
public void show()
{
System.out.println(eno+" "+name+" "+company_name);
}
public static void main( String[] args )
{
Employee e = new Employee();
e.eid = 1;
e.name = "aaa";
e.show();
Employee e2 = new Employee();
e2.eid = 2;
e2.name = “bbb";
e2.show();
}
}
1 aaa A
2 bbb A
static vs instance
public class Test
{
static int x = 1000;
int y = 1000;
public void increment()
{
x++; y++;
}
public static void main( String[] args )
{
Test t1 = new Test();
Test t2 = new Test();
t1.increment();
t2.increment();
System.out.println(t2.y);
System.out.println(Test.x); //accessed without any instance of class.
}
}
o/p: 1001
1002
static method
main() method is declared as static because it is called before any object of the class is created
class Test
{
public static void square(int x)
{
System.out.println(x*x*x);
}
public static void main (String[] arg)
{
square(8); //static method square () is called without any instance of class.
}
}
o/p:64
Static block
Static block is used to initialize static data member. Static block executes before main() method
class Employee
{
int eid;
String name;
static String company_name;
static {
company_name ="A"; //static block invoked before main() method
}
public void show()
{
System.out.println(eid+" "+name+" "+company_name);
}
public static void main( String[] args )
{
Employee e1 = new Employee();
e1.eid = 1;
e1.name = "aaa";
e1.show();
}
}
transient
When an instance variable is declared as transient, then its value doesn't persist when an object is serialized
synchronized
When a method is synchronized it can be accessed by only one thread at a time. We will discuss it in detail in Thread
Volatile modifier tells the compiler that the volatile variable can be changed unexpectedly by other parts of your program. Volatile variables are used in case of multithreading program.
1) private
accessible only within class
class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}
Role of Private Constructor:
If you make any class constructor private, you cannot create the instance of that class from outside the class. For example:
|
class A{
private A()
{
}//private constructor
void msg()
{
System.out.println("Hello java");
}
}
public class Simple{
public static void main(String args[]){
A obj=new A();//Compile Time Error
}
}
Note: A class cannot be private or protected except nested class.
2) default
The default modifier is accessible only within package.
- //save by A.java
- package pack;
- class A{
- void msg(){System.out.println("Hello");}
- }
- //save by B.java
- package mypack;
- import pack.*;
- class B{
- public static void main(String args[]){
- A obj = new A();//Compile Time Error
- obj.msg();//Compile Time Error
- }
- }
3) protected
The protected access modifier is accessible within package and outside the package but through inheritance only
- //save by A.java
- package pack;
- public class A{
- protected void msg(){System.out.println("Hello");}
- }
- //save by B.java
- package mypack;
- import pack.*;
- class B extends A{
- public static void main(String args[]){
- B obj = new B();
- obj.msg();
- }
- }
Output:Hello
4) public
The public access modifier is accessible everywhere. It has the widest scope among all other modifiers.
|
Example of public access modifier
- //save by A.java
- package pack;
- public class A{
- public void msg(){System.out.println("Hello");}
- }
- //save by B.java
- package mypack;
- import pack.*;
- class B{
- public static void main(String args[]){
- A obj = new A();
- obj.msg();
- }
- }
Output:Hello
Modifier | Class | Inner classes (Except local and anonymous classes) | Variable | Method | Constructor | Free floating Code block |
public | Y | Y | Y | Y | Y | N |
protected | N | Y | Y | Y | Y | N |
(friendly)No access modifier | Y | Y (OK for all) | Y | Y | Y | N |
private | N | Y | Y | Y | Y | N |
final | Y | Y (Except anonymous classes) | Y | Y | N | N |
abstract | Y | Y (Except anonymous classes) | N | Y | N | N |
static | N | Y | Y | Y | N | Y (static initializer) |
native | N | N | N | Y | N | N |
transient | N | N | Y | N | N | N |
synchronized | N | N | N | Y | N | Y (part of method, also need to specify an object on which a lock should be obtained) |
volatile | N | N | Y | N | N | N |
1. What is the difference between private, protected, and public?
These keywords are for allowing privileges to components such as java methods and variables.
Public: accessible to all classes
Private: accessible only to the class to which they belong.
-'private' means only the class can access it, not even sub-classes
Protected: accessible to the class to which they belong and any subclasses.
- 'protected' means all classes in the same package (like default) and sub-classes in any package can access the features. But a subclass in another package can access the protected members in the super-class via only the references of subclass or its subclasses. A subclass in the same package doesn't have this restriction. This ensures that classes from other packages are accessing only the members that are part of their inheritance hierarchy.
Encapsulation in Java
Encapsulation is a process of wrapping code and data together into a single unit
Advantage of Encapsulation
By providing only setter or getter method, you can make the class read-only or write-only.
It provides you the control over the data. Suppose you want to set the value of id i.e. greater than 100 only, you can write the logic inside the setter method.
- //save as Student.java
- package com.javatpoint;
- public class Student{
- private String name;
- public String getName(){
- return name;
- }
- public void setName(String name){
- this.name=name
- }
- }
- //save as Test.java
- package com.javatpoint;
- class Test{
- public static void main(String[] args){
- Student s=new Student();
- s.setname("xx”);
- System.out.println(s.getName());
- }
- }
Compile By: javac -d . Test.java
Run By: java com.javatpoint.Test
Run By: java com.javatpoint.Test
output: xx
strictfp keyword
The strictfp keyword ensures that you will get the same result on every platform if you perform operations in the floating-point variable. The precision may differ from platform to platform that is why java programming language have provided the strictfp keyword, so that you get same result on every platform. So, now you have better control over the floating-point arithmetic.
|
Q. Why a non-static variable cannot be referenced from a static context ?
When you try to access a non-static variable from a static context like main method, java compiler throws a message like "a non-static variable cannot be referenced from a static context" This is because non-static variables are related with instance of class(object) and they get created when instance of a class is created by using new operator( which will be compiled after main method). So if you try to access a non-static variable without any instance, compiler will complain because those variables are not yet created and they don't have any existence until an instance is created and associated with it.
class Test
{
int x;
public static void main(String[] args)
{
x=10;
}
}
{
int x;
public static void main(String[] args)
{
x=10;
}
}
compiler error: non-static variable count cannot be referenced from a static context
Q. Why main() method is static in java ?
Because static methods can be called without any instance of a class and main() is called before any instance of a class is created.
No comments:
Post a Comment