Lecture 21-Modifiers
Lecture 21-Modifiers
Java
Object Oriented Programming in Java
There are two types of modifiers in Java: access
modifiers and non-access modifiers.
• The access modifiers in Java specifies the accessibility or scope of a
field, method, constructor, or class. We can change the access level
of fields, constructors, methods, and class by applying the access
modifier on it
Types of Access Modifiers
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
Private
• 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.
Default
//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
}
}
Protected
//save by B.java
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}
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();
}
}