/* COMP 1006 - Day 04 Extra Class (extra stuff about static) mjh-2013 */ /* Mock complex number class in which you have to ask to add a number 3 times before you are allowed to perform an addition. */ public class Extra{ // private attributes can only be accessed from // methods inside the class (static or not) // We cannot access them directly from other classes private int re_; // real and imaginary parts are "private" private int im_; // so that calling calling program cannot // directly access them (and beat out asking game) private static int count = 0; // keeps track of how many times // calling program asks to add // static method for asking to add public static void please(){ // please() is a method in Extra so it can access // the static variable count count += 1; System.out.println("Thank you for asking. You current count is " + count); } public String toString(){ // toString() is a special method that, when defined, // allows us to nicely print something when we try to // print an instance (object) // it can access all attributes of the Extra class // (including the static ones) return "(" + this.re_ + "," + this.im_ + ")"; } // method for adding two Extra numbers public Extra plus(Extra other){ if (count < 3){ System.out.println("you need to ask 3 times!"); return new Extra(0,0); }else{ // using "this" for count is forbidden // because it does not belong to any instance (object) count -= 3; // using "this" here is forbidden this.re_ += other.re_; // using "this" here is optional this.im_ += other.im_; return this; // using "this" here is needed } } // static method for addition // there is no calling object with this method public static Extra add(Extra first, Extra second){ if (count < 3){ // no "this" for count System.out.println("you need to ask 3 times!"); return new Extra(0,0); }else{ count -= 3; // no "this" for count Extra answer = new Extra(); answer.re_ = first.re_ + second.re_; answer.im_ = first.im_ + second.im_; return answer; } } // constructors for complex numbers Extra(){ // zero paramater constructor re_ = 0; // could have put this.re_ = re; im_ = 0; // could have put this.im_ = im; } Extra(int re, int im){ // we could access and modify the static variable // count here, but we have no need this.re_ = re; // I will use "this" when I write code this.im_ = im; // You can do either. Just be consistent } }