/* COMP 1006 - Day 04 Complex Class (with static variable and method) mjh-2013 */ public class Complex2{ int re_; // real part of the number int im_; // imaginary part of the number // static counter to keep track of how many instances are created static int count = 0; // this belongs to the Class and not any instance // method for adding two complex numbers public Complex2 plus(Complex2 other){ this.re_ += other.re_; // using "this" here is optional this.im_ += other.im_; return this; // using "this" here is needed } // another method for addition // this method modifies the calling object // by adding the input number to it public void addWith(Complex2 other){ this.re_ += other.re_; // using "this" is optional this.im_ += other.im_; } // static method for addition // there is no calling object with this method public static Complex2 add(Complex2 first, Complex2 second){ Complex2 answer = new Complex2(); answer.re_ = first.re_ + second.re_; answer.im_ = first.im_ + second.im_; return answer; /* this method can be more compactly written as return Complex2(first.re_ + second.re_, first.im_ + second.im_); */ } // constructors for complex numbers Complex2(){ // zero paramater constructor re_ = 0; // could have put this.re_ = re; im_ = 0; // could have put this.im_ = im; count += 1; // you cannot use "this" with a static variable } Complex2(int re, int im){ this.re_ = re; // I will use "this" when I write code this.im_ = im; // You can do either. Just be consistent count += 1; // You cannot use "this" with a static variable } }