0
0
C Sharp (C#)programming~10 mins

Method overriding with virtual and override in C Sharp (C#) - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to declare a method that can be overridden in a derived class.

C Sharp (C#)
public class Animal {
    public [1] void Speak() {
        Console.WriteLine("Animal sound");
    }
}
Drag options to blanks, or click blank then click option'
Avirtual
Boverride
Cstatic
Dsealed
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'override' in the base class method declaration.
Using 'static' which does not allow overriding.
Using 'sealed' which prevents overriding.
2fill in blank
medium

Complete the code to override the Speak method in the Dog class.

C Sharp (C#)
public class Dog : Animal {
    public [1] void Speak() {
        Console.WriteLine("Bark");
    }
}
Drag options to blanks, or click blank then click option'
Anew
Bsealed
Coverride
Dvirtual
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'virtual' instead of 'override' in the derived class.
Using 'new' which hides the base method but does not override.
Using 'sealed' which is not valid here.
3fill in blank
hard

Fix the error in the derived class method declaration to correctly override the base method.

C Sharp (C#)
public class Cat : Animal {
    public [1] void Speak() {
        Console.WriteLine("Meow");
    }
}
Drag options to blanks, or click blank then click option'
Avirtual
Bsealed
Cstatic
Doverride
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'virtual' in the derived class method.
Using 'static' which is not allowed for overriding.
Omitting the override keyword.
4fill in blank
hard

Fill both blanks to declare a virtual method in the base class and override it in the derived class.

C Sharp (C#)
public class Bird {
    public [1] void Fly() {
        Console.WriteLine("Flying");
    }
}

public class Sparrow : Bird {
    public [2] void Fly() {
        Console.WriteLine("Sparrow flying fast");
    }
}
Drag options to blanks, or click blank then click option'
Avirtual
Bstatic
Coverride
Dsealed
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'static' in either method which prevents overriding.
Using 'sealed' incorrectly.
Omitting the override keyword in the derived class.
5fill in blank
hard

Fill all three blanks to override a virtual method and call the base method inside the override.

C Sharp (C#)
public class Vehicle {
    public [1] void Start() {
        Console.WriteLine("Vehicle starting");
    }
}

public class Car : Vehicle {
    public [2] void Start() {
        [3].Start();
        Console.WriteLine("Car starting with extra steps");
    }
}
Drag options to blanks, or click blank then click option'
Avirtual
Boverride
Cbase
Dsealed
Attempts:
3 left
💡 Hint
Common Mistakes
Not calling the base method inside the override.
Using 'sealed' incorrectly.
Omitting the override keyword in the derived method.