← Back to Scala Course | Chapter 8: Inheritance & Traits | Lesson 6 of 7

Trait बनाम Abstract Class

यह lesson आपको trait और abstract class के बीच चुनने में मदद करता है, जैसे skill card और family blueprint के बीच चुनना। Traits आसानी से mix in होते हैं, जबकि abstract classes shared setup के लिए उपयुक्त हैं।

In this page:

  1. Trait vs Abstract Class

Trait vs Abstract Class

जब आपको constructor parameters चाहिए हों या एक सख्त single-inheritance "is-a" hierarchy model कर रहे हों तो abstract class चुनें; जब आप कई, अन्यथा असंबंधित classes में reusable behavior mix करना चाहते हों तो trait चुनें।

एक class सिर्फ एक abstract class को extend कर सकती है लेकिन किसी भी संख्या में traits mix in कर सकती है। आधुनिक Scala में, behavior share करने के लिए traits ज़्यादा आम tool हैं, और abstract classes को specifically constructor parameters या Java interop की ज़रूरत वाले मामलों के लिए रखा गया है।

Note: एक class ज़्यादा से ज़्यादा एक class/abstract class extend कर सकती है, लेकिन जितने चाहें उतने traits mix in कर सकती है -- यह flexibility आमतौर पर निर्णायक कारक है।

उदाहरण: Trait vs Abstract Class

markup
abstract class Vehicle(val wheels: Int)

trait Honkable {
  def honk(): Unit = println("Honk!")
}

class Car(wheels: Int) extends Vehicle(wheels) with Honkable

object Main extends App {
  val car = new Car(4)
  println(car.wheels)
  car.honk()
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. किसी abstract class का उपयोग करना जब type को कई parents चाहिए हों, जबकि एक class सिर्फ एक को extend कर सकती है।
  2. किसी trait को constructor parameters देना, जिसकी Scala 2 अनुमति नहीं देता और Scala 3 सिर्फ सीमित तरीके से अनुमति देता है।
  3. Vehicle जैसे सख्त "is-a" संबंध वाली किसी चीज़ के लिए trait चुनना, जबकि एक class hierarchy इसे बेहतर तरीके से बताती है।
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.