Difference between revisions of "Polymorphism"

From TRCCompSci - AQA Computer Science
Jump to: navigation, search
Line 1: Line 1:
Polymorphism is the term used to describe one method being able to take more than one type of input to process its code.
+
If you use a class to define a sub class, the sub class will inherit all of the data items and methods defined within the base class. The sub class could however override the inherited version and replace it with the sub classes own version.
<syntaxhighlight lang="csharp" line>public static void Main(string[] args)
+
 
  {
+
==Example==
    int x = divide(15, 4);
+
<syntaxhighlight lang="csharp">  
    double y = divide(2.5, 0.5);
+
Class Mammal{
    Console.WriteLine(x);
+
  private enum hairColour{
    Console.WriteLine(y);
+
      White,
    Console.ReadLine();
+
      Black,
    /* writes:
+
      Brown,
    * 3
+
      Other
    * 5.0
+
  };
    */
+
  public Mammal(){ //Class Constructor
  }
+
      //some code to run when a new instance of the class is created
public static double divide(double a, double b)
+
  }
  {
+
  public override void Move(){
    return a / b;
+
      //Walk code
  }
+
  }
public static int divide(int a, int b)
+
  public enum HairColour{
  {
+
      get{ return hairColour; }
    return a / b;
+
      set{ hairColour = value; }
  }
+
  }
 +
}
 +
</syntaxhighlight>
 +
 
 +
However a Blue Whale is a sub class of Mammal, it will also need to have a Move method. However a Blue Whale obviously can't walk like most over mammals, so its move method will have code to make it swim. A bat is also a mammal, it can crawl (close enough to walk) but will also need to have code to allow it to fly.

Revision as of 21:49, 16 December 2016

If you use a class to define a sub class, the sub class will inherit all of the data items and methods defined within the base class. The sub class could however override the inherited version and replace it with the sub classes own version.

Example

 
Class Mammal{
   private enum hairColour{
      White,
      Black,
      Brown,
      Other
   };
   public Mammal(){ //Class Constructor
      //some code to run when a new instance of the class is created
   }
   public override void Move(){
      //Walk code
   }
   public enum HairColour{
      get{ return hairColour; }
      set{ hairColour = value; }
   }
}

However a Blue Whale is a sub class of Mammal, it will also need to have a Move method. However a Blue Whale obviously can't walk like most over mammals, so its move method will have code to make it swim. A bat is also a mammal, it can crawl (close enough to walk) but will also need to have code to allow it to fly.