static void Main() { IBankAccount venusAccount = new SaverAccount(); IBankAccount jupiterAccount = new GoldAccount(); venusAccount.PayIn(200); venusAccount.Withdraw(100); WriteLine(venusAccount.ToString()); jupiterAccount.PayIn(500); jupiterAccount.Withdraw(600); jupiterAccount.Withdraw(100); WriteLine(jupiterAccount.ToString()); }
static void Main() { IBankAccount venusAccount = new SaverAccount(); //using default constructor, balance is 0 IBankAccount jupiterAccount = new GoldAccount(); /*����instance from a interface instead of class���ĺô�����Inversion Of Control(���Ʒ�ת): * object is typically not known at compile time. you can call only methods that are part of * this interface through these references �� if you want to call any methods implemented by * a class that are not part of the interface, you need to cast the reference to the appropriate type. * But in the example code, you were able to call ToString() (not implemented by IBankAccount) without * any explicit cast, purely because ToString() is a System.Object method, so the C# compiler knows * that it will be supported by any class.*/ venusAccount.PayIn(200); venusAccount.Withdraw(100); Console.WriteLine(venusAccount.ToString()); //override ToString jupiterAccount.PayIn(500); jupiterAccount.Withdraw(600); //withdraw attempt failed jupiterAccount.Withdraw(100); Console.WriteLine(jupiterAccount.ToString()); //Interface references can in all respects be treated as class references �� but the power of an interface reference is that it can refer to any class that implements that interface. }