32.access Modifier in Java
32.access Modifier in Java
Vishnu
Access modifiers are keywords used for defining accessibility of classes, methods and
data members.
1. Private.
2. Default
3. Protected
4. Public
Private:
Data members, methods and constructors that are declared with private access modifier
can be accessed into that class only.
Example:
PrivateAccessModifier.java
packagecom.sst;
1
Sri Sureka Technologies, NearAndraBank,Opposite Geethanjali High School, Near S.R.Nagar
UmeshChandraStachu, S.R.Nagar, Hyderabad-500038, Ph: 040-66616677, Mobile: +91-9885602332.
32. Access modifier By Mr. Vishnu
obj.showRollNo();
}
Output:
at com.javawithease.business.PrivateAccessModifier.main
(PrivateAccessModifier.java:24)
Note: A class can have a private constructor but we cannot create an instance of
that class from outside the class.
PrivateConstructor.java
packagecom.sst;
2
Sri Sureka Technologies, NearAndraBank,Opposite Geethanjali High School, Near S.R.Nagar
UmeshChandraStachu, S.R.Nagar, Hyderabad-500038, Ph: 040-66616677, Mobile: +91-9885602332.
32. Access modifier By Mr. Vishnu
Output:
at com.javawithease.business.PrivateConstructor.main
(PrivateConstructor.java:22)
Default:
Classes, data members, methods and constructors that are not declared with any
access modifier are treated as default. They can be accessed into all classes within the
same package only.
Example 1:
DefaultAccessModifier1.java
packagecom.sst;
3
Sri Sureka Technologies, NearAndraBank,Opposite Geethanjali High School, Near S.R.Nagar
UmeshChandraStachu, S.R.Nagar, Hyderabad-500038, Ph: 040-66616677, Mobile: +91-9885602332.
32. Access modifier By Mr. Vishnu
void showRollNo(){
System.out.println("RollNo = " + rollNo);
}
}
Output:
RollNo = 5
Example 2:
Display.java
packagecom.sst;
Test.java
packagecom.sst;
Output:
Hello vishnu.com
Protected:
Data members, methods and constructors that are declared with protected access
modifier can be accessed into all classes within the same package and only in
subclasses outside the package.
Example 1:
Display.java
packagecom.sst;
System.out.println("Hello vishnu.com");
}
Test.java
package com.sst;
Output:
Hello vishnu.com
Example 2:
Display.java
packagecom.sst;
Test.java
package com.sst;
Output:
Hello vishnu.com
Public:
Classes, data members, methods and constructors that are declared with public access
modifier can be accessed everywhere.
Example:
Display.java
packagecom.sst;
void display(){
System.out.println("Hello vishnu.com");
}
Test.java
package com.sst;
Output:
Hello vishnu.com
8
Sri Sureka Technologies, NearAndraBank,Opposite Geethanjali High School, Near S.R.Nagar
UmeshChandraStachu, S.R.Nagar, Hyderabad-500038, Ph: 040-66616677, Mobile: +91-9885602332.