Back to 课程

Computer-science_A-level_Cie

0% Complete
0/0 Steps
  1. computers-and-components
    6 主题
  2. logic-gates-and-logic-circuits
    2 主题
  3. central-processing-unit-cpu-architecture
    6 主题
  4. assembly-language-
    4 主题
  5. bit-manipulation
    1 主题
  6. operating-systems
    3 主题
  7. language-translators
    2 主题
  8. data-security
    3 主题
  9. data-integrity
    1 主题
  10. ethics-and-ownership
    3 主题
  11. database-concepts
    3 主题
  12. database-management-systems-dbms-
    1 主题
  13. data-definition-language-ddl-and-data-manipulation-language-dml
    1 主题
  14. computational-thinking-skills
    1 主题
  15. algorithms
    14 主题
  16. data-types-and-records
    2 主题
  17. arrays
    2 主题
  18. files
    1 主题
  19. introduction-to-abstract-data-types-adt
    1 主题
  20. programming-basics
    1 主题
  21. constructs
    2 主题
  22. structured-programming
    1 主题
  23. program-development-life-cycle
    2 主题
  24. program-design-
    2 主题
  25. program-testing-and-maintenance
    3 主题
  26. user-defined-data-types
    1 主题
  27. file-organisation-and-access-
    3 主题
  28. floating-point-numbers-representation-and-manipulation
    3 主题
  29. protocols
    2 主题
  30. circuit-switching-packet-switching
    1 主题
  31. processors-parallel-processing-and-virtual-machines
    5 主题
  32. boolean-algebra-and-logic-circuits
    4 主题
  33. purposes-of-an-operating-system-os
    3 主题
  34. translation-software
    3 主题
  35. encryption-encryption-protocols-and-digital-certificates
    3 主题
  36. artificial-intelligence-ai
    4 主题
  37. recursion
    1 主题
  38. programming-paradigms
    4 主题
  39. object-oriented-programming
    7 主题
  40. file-processing-and-exception-handling
    2 主题
  41. data-representation
    5 主题
  42. multimedia
    3 主题
  43. compression
    2 主题
  44. networks-and-the-internet
    11 主题
课 Progress
0% Complete

Polymorphism (OOP)

What is polymorphism?

  • In A Level Computer Science, polymorphism is a concept in programming that allows objects to take on different forms or behaviours

  • Different objects can share the same name or behaviour but can work in different ways

  • It helps make code more flexible, reusable, and easier to maintain

  • It allows flexibility and reusability in programming, making it easier to write and manage code

  • Objects can be treated as belonging to a common group, even if they belong to different classes, making your code more versatile and adaptable to changes

Example 1 – method overloading

Method Overloading Example 1

Method Overloading Example 1

  • In the example above, all three classes all have a method named move(). Polymorphism allows methods to be declared with the same name but execute different code (in this case printing different messages)

  • The override keyword Is used to provide a new implementation for a method that is already defined in the parent class (base class)

Example 2 – method overloading

Method Overloading Example 2

Method Overloading Example 2

  • In the above example both the Motorcycle class and the Car class both inherit from the base class ‘Cars’

  • Objects from the Motorcycle Class and the Car class can call the startEngines() method which will output "Engines Started!"

  • If either of the object types call the displayInfo() method, the program will execute the method from the objects class as it overrides the Vehicle class method

  • For example

    • If a motorcycle object calls the displayInfo() method, "I am a Motorcycle!" will be output

    • If a Car object calls the displayInfo() method, "I am a Car!" will be output

Treating objects as common groups

  • Polymorphism also allows objects of different classes to be treated as objects of a common superclass or base class

  • For example:

    • Vehicle vehicle1 = new Car()

    • Vehicle vehicle2 = new Motorcycle()

  • This allows an array of type Vehicle to store both Motorcycle and Car objects rather than in separate data structures

    • If the vehicle1.displayInfo() method is called, it will still output “I am a Car!”

    • If the vehicle2.displayInfo() method is called, it will still output “I am a Motorcycle!”

  • This flexibility provided by polymorphism are essential for creating more maintainable and modular code

Programming polymorphism (OOP)

How do you program polymorphism?

Run-time polymorphism

  • This happens when a subclass overrides a method defined in a superclass, and the correct version is chosen at run-time, not compile-time

Example scenario: Animal, dog, and cat

Step-by-step logic (pseudocode)

  1. Define a superclass called Animal with a method speak() that does nothing

  2. Create subclasses called Dog and Cat that inherit from Animal

  3. In each subclass, override the speak() method to provide a specific output

  4. Write a function make_sound(animal) that accepts an object of type Animal and calls its speak() method

  5. Create instances of Dog and Cat, and pass them to make_sound()

CLASS Animal METHOD speak() // Empty method (acts as a placeholder) CLASS Dog EXTENDS Animal METHOD speak() OUTPUT "Woof" CLASS Cat EXTENDS Animal METHOD speak() OUTPUT "Meow" PROCEDURE make_sound(animal : Animal) CALL animal.speak() // Create objects
DECLARE myDog : Dog
DECLARE myCat : Cat SET myDog TO NEW Dog()
SET myCat TO NEW Cat() // Demonstrate polymorphism
CALL make_sound(myDog) // Outputs: Woof
CALL make_sound(myCat) // Outputs: Meow
  • Animal is a base class with a speak() method

  • Dog and Cat are subclasses that override the speak() method

  • make_sound() takes an Animal object but calls the correct version of speak() depending on whether it’s a Dog or a Cat

  • This demonstrates run-time polymorphism – the method call is resolved based on the actual type of the object

Python

class Animal: def speak(self): pass # Placeholder method class Dog(Animal): def speak(self): print("Woof") class Cat(Animal): def speak(self): print("Meow") def make_sound(animal): animal.speak() dog = Dog()
cat = Cat() make_sound(dog) # Outputs: Woof
make_sound(cat) # Outputs: Meow
  • This shows method overriding

  • The make_sound() function relies on dynamic method binding

Java

class Animal { public void speak() { // Empty default method }
} class Dog extends Animal { @Override public void speak() { System.out.println("Woof"); }
} class Cat extends Animal { @Override public void speak() { System.out.println("Meow"); }
} public class Main { public static void makeSound(Animal animal) { animal.speak(); } public static void main(String[] args) { Dog dog = new Dog(); Cat cat = new Cat(); makeSound(dog); // Outputs: Woof makeSound(cat); // Outputs: Meow }
}
  • Recognise use of a superclass reference (Animal animal) pointing to a subclass object

  • Polymorphism occurs when animal.speak() dynamically calls the correct overridden method

Worked Example

The child class Helicopter inherits from the parent class Vehicle. A helicopter also has a vertical position and changes the vertical position when it increases speed.

Diagram of a Helicopter class with attributes VerticalPosition, VerticalChange, MaxHeight, and methods Constructor, GetVerticalPosition, IncreaseSpeed.

The Helicopter method IncreaseSpeed() overrides the method from the parent

class and:

  • adds the amount of vertical change to the vertical position

  • adds IncreaseAmount to the current speed

  • adds the updated current speed to the horizontal position.

The vertical position of a helicopter cannot exceed its maximum height.

The current speed of a helicopter cannot exceed its maximum speed.

Write program code for the method IncreaseSpeed() [4]

Answer

  • Method header (overriding where required) with no parameter [1 mark]

  • Adding vertical change to vertical position … [1 mark]

  • …limiting to maximum height [1 mark]

  • Repeating/calling/using the code from original for horizontal increase (in every case) [1 mark]

Example program code:

VB.NET

Overrides Sub IncreaseSpeed() VerticalPosition = VerticalPosition + VerticalChange If VerticalPosition > MaxHeight Then VerticalPosition = MaxHeight End If Me.SetCurrentSpeed(GetCurrentSpeed() + GetIncreaseAmount()) If Me.GetCurrentSpeed() > Me.GetMaxSpeed() Then Me.SetCurrentSpeed(Me.GetMaxSpeed()) End If Me.SetHorizontalPosition(Me.GetHorizontalPosition() + Me.GetCurrentSpeed())
End Sub

Java

public void IncreaseSpeed(){ VerticalPosition = VerticalPosition + VerticalChange; if(VerticalPosition > MaxHeight){ VerticalPosition = MaxHeight; } super.SetCurrentSpeed(super.GetCurrentSpeed() + super.GetIncreaseAmount()); if(super.GetCurrentSpeed() > super.GetMaxSpeed()){ super.SetCurrentSpeed(super.GetMaxSpeed()); } super.SetHorizontalPosition(super.GetHorizontalPosition() + super.GetCurrentSpeed());
}

Python

def IncreaseSpeed(self): self.__VerticalPosition = self.__VerticalPosition + self.__VerticalChange if(self.__VerticalPosition > self.__MaxHeight): self.__VerticalPosition = MaxHeight Vehicle.SetCurrentSpeed(self, Vehicle.GetCurrentSpeed(self) +
Vehicle.GetIncreaseAmount(self)) if(Vehicle.GetCurrentSpeed(self) > Vehicle.GetMaxSpeed(self)): Vehicle.SetCurrentSpeed(self, Vehicle.GetMaxSpeed(self));
Vehicle.SetHorizontalPosition(self, Vehicle.GetHorizontalPosition(self) +
Vehicle.GetCurrentSpeed(self))

Responses

您的邮箱地址不会被公开。 必填项已用 * 标注