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

Abstract Classes क्या हैं

एक abstract class एक आधा-अधूरा plan है जिससे कोई भी वैसे ही नहीं बना सकता। यह कुछ हिस्से उसे extend करने वाली classes के लिए पूरा करने को छोड़ देता है।

In this page:

  1. Abstract Classes
Syntax
scala
abstract class ClassName {
  def abstractMethod(param: Type): ReturnType    // no body
  def concreteMethod(): ReturnType = expression
}

class Child extends ClassName {
  def abstractMethod(param: Type): ReturnType = expression
}

Abstract Classes

एक abstract class को सीधे instantiate नहीं किया जा सकता और यह abstract members (methods या fields जिनका कोई implementation न हो) declare कर सकती है जिन्हें subclasses को ज़रूर प्रदान करना होगा।

Abstract classes फिर भी abstract members के साथ-साथ constructor parameters और concrete (पूरी तरह implemented) methods रख सकती हैं। एक class ज़्यादा से ज़्यादा एक abstract class को extend कर सकती है, जो regular classes जैसा ही single-inheritance rule है।

Warning: किसी abstract Shape class पर new Shape() लिखने की कोशिश करना एक compile error है।

उदाहरण: Abstract Classes

markup
abstract class Shape {
  def area(): Double

  def describe(): Unit = {
    println(s"Area is ${area()}")
  }
}

class Square(side: Double) extends Shape {
  def area(): Double = side * side
}

object Main extends App {
  val sq = new Square(4)
  sq.describe()
}
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. new Shape() से एक instance बनाना, जो fail हो जाता है क्योंकि एक abstract class को instantiate नहीं किया जा सकता।
  2. किसी subclass में abstract method को implement करना भूल जाना, जिससे subclass को भी abstract declare करना पड़ता है।
  3. किसी abstract method को implement करते समय override लिखना, जो optional है, लेकिन ज़रूरी method भूल जाना एक error का कारण बनता है।
🔒

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.