• No results found

I will again start with an example that has the sole purpose of showing the syntax and the example is essentially the same as Exam31. The class Point is now abstract:

public abstract class Point {

private int x; private int y;

public Point(int x, int y) {

this.x = x; this.y = y; }

© Deloitte & Touche LLP and affiliated entities.

360°

thinking.

Discover the truth at www.deloitte.ca/careers

© Deloitte & Touche LLP and affiliated entities.

360°

thinking

.

Discover the truth at www.deloitte.ca/careers

© Deloitte & Touche LLP and affiliated entities.

360°

thinking.

Discover the truth at www.deloitte.ca/careers

© Deloitte & Touche LLP and affiliated entities.

360°

thinking.

public int X { get { return x; } set { x = value; } } public int Y { get { return y; } set { y = value; } }

public override string ToString() {

return string.Format("({0}, {1})", x, y); }

public abstract void Dec(); public abstract void Inc(); }

There are two differences. The class now has two abstract methods Dec() and Inc(). These methods have no code and thus are merely definitions. This means that those who use the class Point knows that these methods exist, but not how they work. The second difference is that the class itself is defined abstract. It must be, and that means that the class can’t be instantiated – you can’t create objects of the type Point

The class NewPoint inherits Point, and must therefore implement the two abstract methods, so they are specific methods that perform something:

public class NewPoint : Point {

public NewPoint(int x, int y) : base(x, y) {

}

public override void Dec() {

--X; --Y; }

public override void Inc() {

++X; ++Y; } }

Note that an abstract method that is implemented in a derived class has to be preceded with the word

Download free eBooks at bookboon.com

C# 1 Introduction to programming and the C# language

115

Abstract classes Below is a Main() method, which uses the class NewPoint:

static void Main(string[] args) {

Point p = new NewPoint(2, 3); Console.WriteLine(p); p.Inc(); Console.WriteLine(p); p.Dec(); Console.WriteLine(p); }

p is a NewPoint object, but it is in the program defined as a Point. It is possible as a NewPoint specifically is a Point, but you should particularly note that even if p is a Point, you can still write

p.Inc();

Since Point has an abstract method Inc(), the compiler knows that a Point object has such a method (although it is defined in a derived class), so the above statement makes sense.

Loan

As an example I will write a class that can represent a loan in a bank. A loan is (in this example) characterized by a principal, a number of periods and an interest rate. I would assume that the interest rate remains constant throughout the payment period, and there is one payment every period on due date and that the payment falls one period after the loan inception. I would also assume that you are interested in the following information

• the nth payment

• repayment at the nth payment

• interest at the nth payment

• outstanding after the nth payment have been paid

The finished program must print a plan for the loan’s amortization that is an overview of how the loan looks after each period.

How to

Corresponding to this a loan could be represented by the following class:

Loan principal: double rate: double periods: int Principal: double Rate: double Periods: int Payment(n): double Interest(n): double Repayment(n): double Outstanding(n):double

Now there are several kinds of loans, and as an example one can look at a serial loan that is characterized by the fact that you for each payment pays the same in repayment plus interest on it at any time due. At such a loan the payment decreases over the repayment period. If, for example you have a serial loan of $1000 and there are 10 periods, you have to pay 10 payments where the repayment each time is $100.

We will turn your CV into

an opportunity of a lifetime

Do you like cars? Would you like to be a part of a successful brand? We will appreciate and reward both your enthusiasm and talent. Send us your CV. You will be surprised where it can take you.

Send us your CV on www.employerforlife.com

Download free eBooks at bookboon.com

C# 1 Introduction to programming and the C# language

117

Abstract classes You can also look at an annuity, which is characterized in that the payment is constant throughout the repayment period. This means that the relationship between interest and repayment are so that in the beginning the interest is a big part of the payment and the repayment is only a small part, and towards the end of the period, the situation is reversed. The relationship between the loans principal, payment and the interest rate can be expressed in the following formula:

rate

rate

payment

principal

periods

+

+

=

1

)

1

(

1

Finally, the outstanding immediately after the payment of the nth payment is calculated as:

rate

rate

payment

rate

principal

restloan

=

(1+

)

n

(1+

)

n

−1

If you look at the above class Loan there is a need for two versions: One for a serial loan and one for an annuity. When two classes have much in common, it is natural to think of a design with a common base class and two derived classes:

Loan principal: double rate: double periods: int Principal: double Rate: double Periods: int Payment(n): double Interest(n): double Repayment(n): double Outstanding(n):double SerialLoan AnnuityLoan Payment(n): double Interest(n): double Repayment(n): double Outstanding(n):double Payment(n): double Interest(n): double Repayment(n): double Outstanding(n):double

The three classes can be implemented in the following manner:

public abstract class Loan {

protected double principal; protected double rate; protected int periods;

public Loan(double principal, double rate, int periods) { this.principal = principal; this.rate = rate; this.periods = periods; }

public double Principal {

get { return principal; } }

public double Rate {

get { return rate; } }

public int Periods {

get { return periods; } }

abstract public double Payment(int n); abstract public double Interest(int n); abstract public double Repayment(int n); abstract public double Outstanding(int n); }

public class SerialLoan : Loan {

public SerialLoan(double principal, double rate, int periods) : base(principal, rate, periods)

{ }

public override double Repayment(int n) {

return principal / periods; }

public override double Outstanding(int n) {

return Repayment(0) * (periods - n); }

public override double Interest(int n) {

return Outstanding(n - 1) * rate; }

public override double Payment(int n) {

return Repayment(n) + Interest(n); }

}

public class AnnuityLoan : Loan {

public AnnuityLoan(double principal, double rate, int periods) : base(principal, rate, periods)

{ }

Download free eBooks at bookboon.com

Click on the ad to read more

C# 1 Introduction to programming and the C# language

119

Abstract classes

public override double Payment(int n) {

return principal * rate / (1 - Math.Pow(1 + rate, -periods)); }

public override double Outstanding(int n) {

return principal * Math.Pow(1 + rate, n) - Payment(0) * (Math.Pow(1 + rate, n) - 1) / rate;

}

public override double Interest(int n) {

return Outstanding(n - 1) * rate; }

public override double Repayment(int n) {

return Payment(n) - Interest(n); }

}

The program must print a plan for the loan’s amortization, which is a table showing the status of the loan each payment:

public class Amortisation {

private Loan loan;

Maersk.com/Mitas

�e Graduate Programme for Engineers and Geoscientists

Month 16

I was a construction

supervisor in

the North Sea

advising and

helping foremen

solve problems

I was a

he

s

Real work International opportunities �ree work placements

al Internationa

or �ree wo

I wanted real responsibili�

I joined MITAS because

Maersk.com/Mitas

�e Graduate Programme for Engineers and Geoscientists

Month 16

I was a construction

supervisor in

the North Sea

advising and

helping foremen

solve problems

I was a

he

s

Real work International opportunities �ree work placements

al Internationa

or �ree wo

I wanted real responsibili�

I joined MITAS because

Maersk.com/Mitas

�e Graduate Programme for Engineers and Geoscientists

Month 16

I was a construction

supervisor in

the North Sea

advising and

helping foremen

solve problems

I was a

he

s

Real work International opportunities �ree work placements

al Internationa

or �ree wo

I wanted real responsibili�

I joined MITAS because

Maersk.com/Mitas

�e Graduate Programme for Engineers and Geoscientists

Month 16

I was a construction

supervisor in

the North Sea

advising and

helping foremen

solve problems

I was a

he

s

Real work International opportunities �ree work placements

al Internationa

or �ree wo

I wanted real responsibili�

I joined MITAS because

public Amortisation(Loan loan) {

this.loan = loan; }

public void Print() {

Console.WriteLine("Principal: {0, 10:F}", loan.Principal); Console.WriteLine("Rate of interest: {0, 10:F}", loan.Rate); Console.WriteLine("Number of periods: {0, 10:D}\n", loan.Periods); Console.WriteLine(

"Periods Payment Repayment Interest Outstanding"); for (int n = 1; n <= loan.Periods; ++n)

Console.WriteLine("{0, 7:D}{1, 15:F}{2, 15:F}{3, 15:F}{4, 15:F}", n,

loan.Payment(n), loan.Repayment(n), loan.Interest(n), loan.Outstanding(n)); }

}

Explanation

Note first that the class Loan is defined abstract. It must be because it has abstract methods. An abstract method is a method that is not defined – its code is not written. In this case there are four abstract methods. The reason that the methods are abstract is that how for example the payment is calculated depends on what kind of loan it is. The method can only be implemented when you know what kind of loan you are talking about. An abstract method is simply a prototype definition in which a method is defined by its name, return type and parameters, but its body is missing.

Loan is a type, and even though it is abstract, and you thus can’t create objects of type Loan, the type can for example be used as a type of an argument to a method. Everybody who gets the informed that they are dealing with something of the type Loan knows that it is something that beyond the three properties have four methods, Payment(), Interest(), Repayment() and Outstanding(), and you can use the four abstract methods as if they existed.

The class SerialLoan inherits Loan, and thus it is up to class SerialLoan to implement the four abstract methods so that SerialLoan is a concrete class. The class SerialLoan can implement the abstract methods, because it has the needed knowledge – a knowledge not known in the class Loan. The implementations of the abstract methods are trivial, but note that a SerialLoan is specifically a Loan.

The class AnnuityLoan is also easy to implement, and it consists simply of writing the above formulas in C#. Here you should note the method Pow(), which is a static method of the Math class, which raises an argument in a power.

Finally, there is class Amortisation, which can print a plan for a loan’s amortization. Here you should note that the class has an instance variable of type Loan, which is initialized in the constructor. So you can have a variable whose type is an abstract class, since concrete objects of types respectively SerialLoan

and AnnuityLoan also is of the type Loan. Please note that the class Amortisation know nothing about the specific loan type, but nevertheless one can write method Print(), since all methods are defined for the abstract type of Loan. The class Amortisation will also support and work on new types of loans as long as they inherit the class Loan.

Download free eBooks at bookboon.com

C# 1 Introduction to programming and the C# language

121

Abstract classes

Test

If you test the above classes with the following program:

class Program {

static void Main(string[] args) {

Amortisation table1 = new Amortisation(new SerialLoan(10000, 0.02, 10)); Amortisation table2 = new Amortisation(new AnnuityLoan(10000, 0.02, 10)); table1.Print();

table2.Print(); }

}

you get the following result:

Comment

In the last examples, there typically have been a number of classes and in this case four classes in addition to the Main program. In all examples, the classes code have been in the same file, but as the examples become larger, there is not a viable option for the sake of clarity. Many choose to consistently place each a class in its own file and it is quite a sensible strategy, since it is a way for small source files, which are much easier to understand.

Comment

Note in particular that a class may be abstract, although it has not abstract methods. It can be used if you want to ensure that a class can not be instantiated.