Cards (5)

  • What is Polymorphism
    • 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 
  • Method Overloading #1

    • In the example below, 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)
  • Method Overloading #2
    • In the below 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
  • Treating objects as common groups #1
    • 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() 
    • Treating objects as common groups 
    • 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