Access Modifiers in Java
Access Modifiers in Java. In this Article i will explain what is Access Modifiers by stepping through the sample program below
In the sample program below, first I will create a main class named “car ” .Then i will create a class call “accessModifier” to access the class ” car “.
Class Car
- First i declare no modifier variable ” engineVolume , carSpeed”
- Then I declare a private Variable ” privateCar”
- Then I declare a private Variable ” publicCar”
- Lastly i declare a protected Variable “protectedCar”
- I create an Empty Constructor
- Create a setter and getter to read and write the “privateCar” Variable.
- Create an increaseSpeed function
- Create a decreaseSpeed function,
package Automation; public class car { // Car Engine Volume // No Modifier - accessible in the same package int engineVolume; int carSpeed; // private - accessible in this class only private int privateCar =20; //public - can be Access in any where Java, any Packages public int publicCar=15; //protected-Can only be access same package and in sub classes protected int protectedCar =40; // create Object Constructor ,this(0) means no parameter needed public car(){ } // Getter - To access the privateCar value // Setter - To overwrite the Private Car Value. public void setPrivateCar(int Pspeed) { this.privateCar = Pspeed; } public int getPrivateCar() { return privateCar; } // Create increase Speed Function public void increaseSpeed (){ carSpeed++; System.out.println("Increasing the Car Speed"); } public void decreaseSpeed (){ carSpeed--; System.out.println("Decreasing the Car Speed"); } }
accessModifier
- I create a new car object called “secondCar”
- Access the ” No Modifier ” Variable “carSpeed”
- Access the privateCar variable through “secondCar.getPrivateCar()”
- Write a new Value into privateCar variable using ” secondCar.setPrivateCar(1000);”
- Access the publicCar and the protectedCar Variable.
package Automation; public class accessModifier { public static void main(String[] args) { car secondCar = new car(); secondCar.increaseSpeed(); // No Modifier secondCar.carSpeed = 10; System.out.println(secondCar.carSpeed); // Access the Private Modifier System.out.println(secondCar.getPrivateCar()); //Overwrite the variable inside the Private Modifier secondCar.setPrivateCar(1000); //After Overwrite the variable inside the Private Modifier , Access the Varible again System.out.println(secondCar.getPrivateCar()); // Print Out Public Car System.out.println(secondCar.publicCar); // Print out Protected Car System.out.println(secondCar.protectedCar); secondCar.decreaseSpeed(); } }
No | Access Modifier | Inside Class | Inside Package | Outside Package by Sub Class | Outside Package |
---|---|---|---|---|---|
1 | Private | Y | N | N | N |
2 | Default | Y | Y | N | N |
3 | Protected | Y | Y | Y | N |
4 | Public | Y | Y | Y | Y |
Check Out Inheritance in Java Here