Global variables in Java

后端 未结 24 2087
青春惊慌失措
青春惊慌失措 2020-11-22 11:56

How do you define Global variables in Java ?

24条回答
  •  迷失自我
    2020-11-22 12:29

    // Get the access of global while retaining priveleges.
    // You can access variables in one class from another, with provisions.
    // The primitive must be protected or no modifier (seen in example).
    
    // the first class
    public class farm{
    
      int eggs; // an integer to be set by constructor
      fox afox; // declaration of a fox object
    
      // the constructor inits
      farm(){
        eggs = 4;
        afox = new fox(); // an instance of a fox object
    
        // show count of eggs before the fox arrives
        System.out.println("Count of eggs before: " + eggs);
    
        // call class fox, afox method, pass myFarm as a reference
        afox.stealEgg(this);
    
        // show the farm class, myFarm, primitive value
        System.out.println("Count of eggs after : " + eggs);
    
      } // end constructor
    
      public static void main(String[] args){
    
        // instance of a farm class object
        farm myFarm = new farm();
    
      }; // end main
    
    } // end class
    
    // the second class
    public class fox{
    
      // theFarm is the myFarm object instance
      // any public, protected, or "no modifier" variable is accessible
      void stealEgg(farm theFarm){ --theFarm.eggs; }
    
    } // end class
    

提交回复
热议问题