v Access Specifier
- Public
- Private
- Protected
- Default
1. Public :
- Public member access with in the class with in the same package and with in another package.
- Example:
When methods, variables, classes, and so on are declared public, then we can access them from anywhere. The public access modifier has no scope restriction. For example,
// Animal.java file
// public class
publicclass Animal{
// public variable
publicintlegCount;
// public method
public void display(){
System.out.println("I am an animal.");
System.out.println("I have "+ legCount +" legs.");
}
}
// Main.java
publicclass Main{
public static void main( String[] args ){
// accessing the public class
Animal animal =newAnimal();
// accessing the public variable
animal.legCount =4;
// accessing the public method
animal.display();
}
}
Output:
I am an animal.
I have 4 legs.
2. Private :
-
Private member only access in class.
Example:
class Data {
// private variable
privateString name;
}
publicclass Main{
public static void main(String[] main){
// create an object of Data
Data d =newData();
// access private variable and field from another class
d.name ="Tech Ocean";
}
}
Output:
Main.java:18: error: name has private access in Data
d.name = "Tech Ocean";
-> The error is generated because we are trying to access the private variable of the Data class from the Main class.
-> You might be wondering what if we need to access those private variables. In this case, we can use the getters and setters method. For example,
class Data {
privateString name;
// getter method
public String getName(){
returnthis.name;
}
// setter method
public void setName(String name){
this.name= name;
}
}
publicclass Main{
public static void main(String[] main){
Data d =newData();
// access the private variable using the getter and setter
d.setName("Tech Ocean");
System.out.println(d.getName());
}
}
Output:
Tech Ocean
3. Protected :
-
Protected member access from derived/child class .
-
When methods and data members are declared protected,
we can access them within the same package as well as from subclasses. For
example,
class Animal {
// protected method
protected void display(){
System.out.println("I am an animal");
}
}
class Dog extends Animal {
public static void main(String[] args){
// create an object of Dog class
Dog dog =newDog();
// access protected method
dog.display();
}
}
Output:
I am an animal
4. Default :
-
Default member access from same class and in the
same package.
Example:
class Data {
// default variable
String name;
}
publicclass Main{
public static void main(String[] main){
// create an object of Data
Data d =newData();
// access default variable and field from another class
d.name ="Tech Ocean";
System.out.println(d.name());
}
}
Output:
Tech Ocean
👍
ReplyDelete