Access Control of Parent Variables

  1. The 4th (and final) access control modifier in is protected

    Example: protected access
       public class BankAccount
       {
          protected double balance; // Variable with "protected" access  
          ....
       }
    
    

  2. Rules for accessing protected variables/methods:

  3. Example:

    Example: accesing protected variables
    
        package mylib.finance;
    
        public class BankAccount
        {
           protected double balance;      
           ...
        }
    
    

    Example: accesing protected variables
    
        package mylib.finance;
    
        public class myProgram
        {
           public static void main(String args[])
           {
    	  BankAccount myAccount = new BankAccount(1000);
    
    	  myAccount.balance = myAccount.balance + 100000;
    		// Direct access allowed, because in same package   
           }
        }
    
    

    Example: accesing protected variables
    
        package a.different.package;
    
        public class myProgram extends BankAccount
        {
           public static void main(String args[])
           {
    	  BankAccount myAccount = new BankAccount(1000);
    
    	  myAccount.balance = myAccount.balance + 100000;
    		// Direct access allowed, class is child of BankAccount   
           }
        }
    
    

    Example: accesing protected variables
    
        package a.different.package;
    
        public class myProgram
        {
           public static void main(String args[])
           {
    	  BankAccount myAccount = new BankAccount(1000);
    
    	  myAccount.balance = myAccount.balance + 100000;    
    		// ERROR ! Direct access NOT allowed   
           }
        }
    
    

  4. Programming Advice: