Csharp/C Sharp/Class Interface/Abstract Class

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Abstract Classes and Methods

<source lang="csharp">

using System; abstract public class MotorVehicle {

   public string make;
   public string model;
   public MotorVehicle(string make, string model) {
       this.make = make;
       this.model = model;
   }
   abstract public void Accelerate();

} public class Product : MotorVehicle {

   public Product(string make, string model) :
       base(make, model) {
       // do nothing
   }
   public override void Accelerate() {
       Console.WriteLine("In Product Accelerate() method");
       Console.WriteLine(model + " accelerating");
   }

}

class MainClass {

   public static void Main() {
       Product myProduct = new Product("Toyota", "MR2");
       myProduct.Accelerate();
   }

}

</source>


Bank Account class is abstract since there is no single implementation for Withdrawal

<source lang="csharp"> using System; public class MainClass {

   public static void Main(string[] strings) {
       SavingsAccount sa = new SavingsAccount();
       sa.Withdrawal(100);
       CheckingAccount ca = new CheckingAccount();
       ca.Withdrawal(100);
   }

} abstract public class BankAccount {

   abstract public void Withdrawal(double dWithdrawal);

} public class SavingsAccount : BankAccount {

   override public void Withdrawal(double dWithdrawal) {
       Console.WriteLine("Call to SavingsAccount.Withdrawal()");
   }

} public class CheckingAccount : BankAccount {

   override public void Withdrawal(double dWithdrawal) {
       Console.WriteLine("Call to CheckingAccount.Withdrawal()");
   }

}

</source>


Create an abstract class

<source lang="csharp"> /* C#: The Complete Reference by Herbert Schildt Publisher: Osborne/McGraw-Hill (March 8, 2002) ISBN: 0072134852

  • /

// Create an abstract class.

using System;

abstract class TwoDShape {

 double pri_width;  // private 
 double pri_height; // private 
 string pri_name;   // private 
 
 // A default constructor.  
 public TwoDShape() {  
   width = height = 0.0;  
   name = "null";  
 }  
 
 // Parameterized constructor.  
 public TwoDShape(double w, double h, string n) {  
   width = w;  
   height = h;  
   name = n;  
 }  
 
 // Construct object with equal width and height.  
 public TwoDShape(double x, string n) {  
   width = height = x;  
   name = n;  
 }  
 
 // Construct an object from an object.  
 public TwoDShape(TwoDShape ob) {  
   width = ob.width;  
   height = ob.height;  
   name = ob.name;  
 }  
 
 // Properties for width, height, and name 
 public double width { 
   get { return pri_width; } 
   set { pri_width = value; } 
 } 

 public double height { 
   get { return pri_height; } 
   set { pri_height = value; } 
 } 

 public string name { 
   get { return pri_name; } 
   set { pri_name = value; } 
 } 
 
 public void showDim() {  
   Console.WriteLine("Width and height are " +  
                      width + " and " + height);  
 }  
 
 // Now, area() is abstract. 
 public abstract double area(); 

}

// A derived class of TwoDShape for triangles. class Triangle : TwoDShape {

 string style; // private 
   
 // A default constructor.  
 public Triangle() {  
   style = "null";  
 }  
 
 // Constructor for Triangle.  
 public Triangle(string s, double w, double h) : 
   base(w, h, "triangle") {  
     style = s;   
 }  
 
 // Construct an isosceles triangle.  
 public Triangle(double x) : base(x, "triangle") {  
   style = "isosceles";   
 }  
 
 // Construct an object from an object.  
 public Triangle(Triangle ob) : base(ob) {  
   style = ob.style;  
 }  
 
 // Override area() for Triangle. 
 public override double area() {  
   return width * height / 2;  
 }  
 
 // Display a triangle"s style. 
 public void showStyle() {  
   Console.WriteLine("Triangle is " + style);  
 }  

}

// A derived class of TwoDShape for rectangles. class Rectangle : TwoDShape {

 // Constructor for Rectangle.  
 public Rectangle(double w, double h) :  
   base(w, h, "rectangle"){ }  
 
 // Construct a square.  
 public Rectangle(double x) :  
   base(x, "rectangle") { }  
 
 // Construct an object from an object.  
 public Rectangle(Rectangle ob) : base(ob) { }  
 
 // Return true if the rectangle is square. 
 public bool isSquare() {   
   if(width == height) return true;   
   return false;   
 }   
    
 // Override area() for Rectangle. 
 public override double area() {   
   return width * height;   
 }   

}

public class AbsShape {

 public static void Main() {  
   TwoDShape[] shapes = new TwoDShape[4];  
 
   shapes[0] = new Triangle("right", 8.0, 12.0);  
   shapes[1] = new Rectangle(10);  
   shapes[2] = new Rectangle(10, 4);  
   shapes[3] = new Triangle(7.0);  
 
   for(int i=0; i < shapes.Length; i++) {  
     Console.WriteLine("object is " + shapes[i].name);  
     Console.WriteLine("Area is " + shapes[i].area());  
 
     Console.WriteLine();    
   }  
 }  

}


      </source>


Demostrates the use of an abstract class, including an abstract method and abstract properties

<source lang="csharp"> /* C# Programming Tips & Techniques by Charles Wright, Kris Jamsa Publisher: Osborne/McGraw-Hill (December 28, 2001) ISBN: 0072193794

  • /

// // Abstract.cs -- Demostrates the use of an abstract class, including // an abstract method and abstract properties. // // Compile this program with the following command line: // C:>csc Abstract.cs // namespace nsAbstract {

   using System;
   
   public class AbstractclsMain
   {
       static public void Main ()
       {
           // Create an instance of the derived class.
           clsDerived derived = new clsDerived (3.14159);
           // Calling GetAbstract() actually calls the public method in the
           // base class. There is no GetAbstract() in the derived class.
           derived.GetAbstract();
       }
   }
   // Declare an abstract class
   abstract class clsBase
   {
       // Declare an abstract method. Note the semicolon to end the declaration
       abstract public void Describe();
       // Declare an abstract property that has only a get accessor. 
       // Note that you
       // do not prove the braces for the accessor
       abstract public double DoubleProp
       {
           get;
       }
       // Declare an abstract property that has only a set accessor.
       abstract public int IntProp
       {
           set;
       }
       // Declare an abstract propety that has both get and set accessors. Note
       // that neither the get or set accessor may have a body.
       abstract public string StringProp
       {
           get;
           set;
       }
       // Declare a method that will access the abstract members.
       public void GetAbstract ()
       {
           // Get the DoubleProp, which will be in the derived class.
           Console.WriteLine ("DoubleProp = " + DoubleProp);
           // You can only set the IntProp value. The storage is in the
           // derived class.
           IntProp = 42;
           // Set the StringProp value
           StringProp = "StringProperty actually is stored in " +
                        "the derived class.";
           // Now show StringProp
           Console.WriteLine (StringProp);
           
           // Finally, call the abstract method
           Describe ();
       }
   }
   // Derive a class from clsBase. You must implement the abstract members
   class clsDerived : clsBase
   {
       // Declare a constructor to set the DoubleProp member
        public clsDerived (double val)
        {
            m_Double = val;
        }
       // When you implement an abstract member in a derived class, you may not
       // change the type or access level.
       override public void Describe()
       {
           Console.WriteLine ("You called Describe() from the base " +
                              "class but the code body is in the \r\n" +
                              "derived class");
           Console.WriteLine ("m_Int = " + m_Int);
       }
       // Implement the DoubleProp property. This is where you provide a body
       // for the accessors.
       override public double DoubleProp
       {
           get {return (m_Double);}
       }
       // Implement the set accessor for IntProp.
       override public int IntProp
       {
           set {m_Int = value;}
       }
       
       // Implement StringProp, providing a body for both the get
       // and set accessors.
       override public string StringProp
       {
           get {return (m_String);}
           set {m_String = value;}
       }
       
       // Declare fields to support the properties.
       private double m_Double;
       private int m_Int;
       private string m_String;
   }

}


      </source>


Illustrates abstract classes and methods

<source lang="csharp"> /* Mastering Visual C# .NET by Jason Price, Mike Gunderloy Publisher: Sybex; ISBN: 0782129110

  • /

/*

 Example7_9.cs illustrates abstract classes and methods
  • /

using System;

// declare the abstract MotorVehicle class abstract class MotorVehicle {

 // declare the fields
 public string make;
 public string model;
 // define a constructor
 public MotorVehicle(string make, string model)
 {
   this.make = make;
   this.model = model;
 }
 // declare the abstract Accelerate() method (no code)
 abstract public void Accelerate();

}

// declare the Car class (derived from MotorVehicle) class Car : MotorVehicle {

 // define a constructor
 public Car(string make, string model) :
 base(make, model)
 {
   // do nothing
 }
 // override the Accelerate() method (contains code)
 public override void Accelerate()
 {
   Console.WriteLine("In Car Accelerate() method");
   Console.WriteLine(model + " accelerating");
 }

}

public class Example7_9 {

 public static void Main()
 {
   // create a Car object
   Console.WriteLine("Creating a Car object");
   Car myCar = new Car("Toyota", "MR2");
   // call the Car object"s Accelerate() method
   Console.WriteLine("Calling myCar.Accelerate()");
   myCar.Accelerate();
 }

}


      </source>


Test abstract class

<source lang="csharp"> /* Learning C# by Jesse Liberty Publisher: O"Reilly ISBN: 0596003765

  • /
using System;
abstract class Window
{
    // constructor takes two integers to
    // fix location on the console
    public Window(int top, int left)
    {
        this.top = top;
        this.left = left;
    }
    // simulates drawing the window
    // notice: no implementation
    abstract public void DrawWindow();
    protected int top;
    protected int left;
}
// ListBox derives from Window
class ListBox : Window
{
    // constructor adds a parameter
    public ListBox(
        int top,
        int left,
        string contents):
        base(top, left)  // call base constructor
    {
        listBoxContents = contents;
    }
    // an overridden version implementing the
    // abstract method
    public override void DrawWindow()
    {
        Console.WriteLine ("Writing string to the listbox: {0}",
            listBoxContents);
    }
    private string listBoxContents;  // new member variable
}
class Button : Window
{
    public Button(
        int top,
        int left):
        base(top, left)
    {
    }
    // implement the abstract method
    public override void DrawWindow()
    {
        Console.WriteLine("Drawing a button at {0}, {1}\n",
            top, left);
    }
}
public class TesterAbstractClass
{
    static void Main()
    {
        Window[] winArray = new Window[3];
        winArray[0] = new ListBox(1,2,"First List Box");
        winArray[1] = new ListBox(3,4,"Second List Box");
        winArray[2] = new Button(5,6);
        for (int i = 0;i < 3; i++)
        {
            winArray[i].DrawWindow();
        }
    }
}
          
      </source>