// Mixing.java // demonstrates encapsulation, $static$ // Originally written by Raju Rohde, Fall 2000 /* This is an example on how to write static/non-static methods and how you can pass reference variables to methods Write a class Juice that is has 1. instance variables: o vol (volume) o sugar (amount of sugar in % of vol) o water (amount of water in % of vol) 2. constructor that initializes the instance variables 3. instance method, mix1, that mixes one's juice with another juice and returns a new juice 4. class method, mix2, that mixes two jucies and returns a new juice Write a class Mixing that 1. instantiates 2 objects of class Juice (assign some reasonable numbers to the instance variable) 2. "mix" those 2 instantiates juices by calling both the instance method mix1 and the class method mix2. Note: Juices produced by methods mix1 and mix2 should taste the same. */ class Juice{ // instance variables private double vol; private double sugar; private double water; // constructor public Juice(double v, double s, double w) { vol=v; sugar=s; water=w; } // getters public double getVolume() { return vol; } public double getSugar() { return sugar; } public double getWater() { return water; } // instance method approach: mix ingredients // Mix current Juice's ingredients and with another Juice's ingredients: public Juice mix1(Juice j){ double volmix= j.vol + vol; double sugmix= (j.sugar + sugar)/volmix; double watmix= (j.water + water)/volmix; return new Juice(volmix,sugmix,watmix); } // class method: mix ingredients // Mix 2 Juice's ingredients together: public static Juice mix2(Juice j1,Juice j2){ double volmix= j1.vol + j2.vol; double sugmix= (j1.sugar + j2.sugar)/volmix; double watmix= (j1.water + j2.water)/volmix; return new Juice(volmix,sugmix,watmix); } } class Mixing{ public static void main(String [] args){ // Instantiate two "reasonable" drinks of class Juice: Juice drink1=new Juice(100,30,70); Juice drink2=new Juice(150,40,110); // Instantiate first mix by calling the instance method: Juice mixdrink1=drink1.mix1(drink2); System.out.println("mixdrink1: vol = " + mixdrink1.getVolume() ); System.out.println(" sugar= " + mixdrink1.getSugar() ); System.out.println(" water= " + mixdrink1.getWater() ); // Instantiate second mix by calling the class method: Juice mixdrink2=Juice.mix2(drink1,drink2); System.out.println("mixdrink2: vol = " + mixdrink2.getVolume() ); System.out.println(" sugar= " + mixdrink2.getSugar() ); System.out.println(" water= " + mixdrink2.getWater() ); } } /* Output: mixdrink1: vol = 250.0 sugar= 0.28 water= 0.72 mixdrink2: vol = 250.0 sugar= 0.28 water= 0.72 */