Friday, October 12, 2012

Interfaces



C# Examples: Interfaces

 
Introduction

This example uses interfaces:
  • One interface introduces two properties
  • One interface introduces a method
  • One interface inherits from two interfaces but adds a new property
  • One class inherits from an interface
Source File: Preparation.cs
public enum SportCategory
{
 SinglePlayer,
 Collective,
 Unknown
}

public interface ICourtDimensions
{
 double Length { get; set; }
 double Width  { get; set; }
}

public interface IBall
{
 int NumberOfPlayers
 {
  get;
  set;
 }

 string NameOfSport
 {
  get;
 }

 void SportCharacteristics();
}

public interface ISportType : IBall, ICourtDimensions
{
 SportCategory Type
 {
  get;
 }
}
Source File: Sport.cs
using System;

public class SportBall : ISportType
{
 int players;
 string sport;
 SportCategory _type;
 double Len;
 double Wdt;
    
 public SportBall(int nbr, SportCategory tp, string name)
 {
  players = nbr;
  _type   = tp;
  sport   = name;
 }

 public int NumberOfPlayers
 {
  get { return players;}
  set { players = value;}
 }

 public string NameOfSport
 {
  get { return sport; }
 }

 public SportCategory Type
 {
  get { return _type; }
 }

 public double Length
 {
  get { return Len; }
  set { Len = value; }
 }

 public double Width
 {
  get { return Wdt; }
  set { Wdt = value; }
 }

 public void SportCharacteristics()
 {
  Console.WriteLine("Sport Characteristics");
  Console.WriteLine("Name of Sport: {0}", NameOfSport);
  Console.WriteLine("Type of Sport: {0}", Type);
  Console.WriteLine("# of Players:  {0}", NumberOfPlayers);
  Console.WriteLine("Court Dimensions: {0}m x {1}m", Len, Wdt);
 }
}
Source File: Exercise.cs
using System;

class Exercise
{
 static void Main()
 {
  SportBall volley = new SportBall(6, SportCategory.Collective, "Volley Ball");
  volley.Length = 18;
  volley.Width  = 9;
  volley.SportCharacteristics();

  Console.WriteLine();

 SportBall tennis = new SportBall(1, SportCategory.SinglePlayer, "Table Tennis");
  tennis.Length = 23.7;
  tennis.Width  = 8.25;
  tennis.SportCharacteristics();

  Console.WriteLine();
 }
}

This would produce:
Sport Characteristics
Name of Sport: Volley Ball
Type of Sport: Collective
# of Players:  6
Court Dimensions: 18m x 9m

Sport Characteristics
Name of Sport: Table Tennis
Type of Sport: SinglePlayer
# of Players:  1
Court Dimensions: 23.7m x 8.25m

No comments:

Post a Comment