Java Tutorial #18 — Access Modifiers; Working with / around them


Topics discussed: Access modifiers, public, private, static
Source Code Available Here


Access modifiers
Access modifiers are our way of sectioning off our program and making it harder to accidentally use / misuse methods not contained within the calling class. There are 4 access modifiers and they basically work like this:

  1. Public: Public as an access modifier means that the ANYTHING can call on your class / function. This means that anyone / any function can call it for any reason, we’ll see why that’s a problem later on.
  2. Protected: Protected is the exact same as public except that it cannot be called by anything, only things that exist in the same package / class / subclass as where the call originated from.
  3. not specified: Only accepts calls from the class / package and no subclasses.
  4. Private: Only accepts calls from within the class.

  5. Using public as an access modifier
    When we use public as an access modifier, the entire program (or any other program) can call upon our methods / objects if they are familiar with our interface. We might get into external calls at a much later lesson but for now let’s look at internal same-project calls:

    /////  Javafile.java /////
    
    int x= 1, y=7;
    //the syntax to call a public method in another file is methodFile.methodName
    sum = methodFile.sum(x,y)
    
    /////methodFile.java/////
    
    public static int sum(int x, int y){
    return (x+y);//Will return the sum of x+y to Javafile.java
    }
    


    Using private as a modifier
    If you’re in doubt about whether or not you should be using private as a modifier, you should be using private as a modifier. When we get into larger programs in the future with 4 or 5 different files, data will be moving all over the place, and controlling the flow of that data is extremely important. The only way to ensure that nothing gets passed incorrectly is to safeguard methods / classes that we want to keep safe.