Object Oriented Programming

Access Modifiers in Java

Access modifiers restrict or permit direct access to a member (method, class, field, etc.) outside of a class or scope.


Syntax
modifier memberDeclaration; //memberDeclaration is the method, class, variable, or other member declaration

Notes

Members with the 'public' modifier can be accessed directly outside of the class.

Members with the 'private' modifier can only be accessed within the class

Members with the 'protected' modifier can be accessed within the class, an imported package, and within a subclass.


Example
public class Car { 
    private int speed; 
    public int wheels;
    /*these methods can access and modify the private variable
    because they are within its class */
    public Car(int carSpeed) { 
        speed = carSpeed; 
        wheels = 4;
    }  
    //this public method is a 'getter', it returns the value contained in a private variable
    public int getSpeed() { 
        return speed;
    }
    public void carBrake(int slow) { 
        speed -= slow; 
    }
}
 
Car sedan = new Car(80);
//wheels is a public variable, so it can be accessed directly outside the class itself
System.out.println("Number of wheels: " + sedan.wheels);
 
//Speed is a private variable, so it cannot be accessed directly
System.out.println("Speed: " + sedan.speed); //will not compile
//Instead, a public method within the class is used to access the variable's value
System.out.println("Speed: " + sedan.getSpeed()); //will compile

< Try Catch Block   |   Constructor >

© 2018 SyntaxDB. All Rights Reserved.