Abstract Classes क्या हैं
एक abstract class एक आधा-अधूरा plan है जिससे कोई भी वैसे ही नहीं बना सकता। यह कुछ हिस्से उसे extend करने वाली classes के लिए पूरा करने को छोड़ देता है।
In this page:
Syntax
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
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()
}
Login to try C/C++/Java/PHP code in the editor
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. #}
आम गलतियां
new Shape()से एक instance बनाना, जो fail हो जाता है क्योंकि एक abstract class को instantiate नहीं किया जा सकता।- किसी subclass में abstract method को implement करना भूल जाना, जिससे subclass को भी
abstractdeclare करना पड़ता है। - किसी abstract method को implement करते समय
overrideलिखना, जो optional है, लेकिन ज़रूरी method भूल जाना एक error का कारण बनता है।
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: