Bird
0
0

How can inheritance help reduce code duplication when creating a set of classes representing different types of vehicles with shared properties like speed and color?

hard🚀 Application Q9 of 15
C Sharp (C#) - Inheritance
How can inheritance help reduce code duplication when creating a set of classes representing different types of vehicles with shared properties like speed and color?
ABy using interfaces only without base class
BBy defining a base class Vehicle with common properties, then inheriting it in specific vehicle classes
CBy writing all properties separately in each vehicle class
DBy copying code manually between classes
Step-by-Step Solution
Solution:
  1. Step 1: Identify shared properties among vehicles

    Speed and color are common to all vehicles, so they belong in a base class.
  2. Step 2: Use inheritance to share properties

    By defining a base class Vehicle with common properties, then inheriting it in specific vehicle classes correctly suggests creating a Vehicle base class with shared properties and inheriting it in specific vehicle classes to avoid duplication.
  3. Final Answer:

    By defining a base class Vehicle with common properties, then inheriting it in specific vehicle classes -> Option B
  4. Quick Check:

    Base class shares common code, reducing duplication [OK]
Quick Trick: Put shared properties in base class to avoid repetition [OK]
Common Mistakes:
MISTAKES
  • Duplicating properties in every class
  • Using interfaces without shared implementation
  • Copy-pasting code instead of inheriting

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More C Sharp (C#) Quizzes