Lesson 28 of 34

Inheritance: extends और super

10 min 35 XP

extends से child class parent के fields और methods inherit करती है। super(...) parent constructor को call करता है। Child किसी parent method को override करके उसे अपने तरीके से कर सकती है।

Example: edit me and press Run

Output Loading Java (first time takes a few seconds)
Press Run to see the result here.

Java class सिर्फ़ एक class को extend कर सकती है (classes का multiple inheritance नहीं)। इसका हल interfaces हैं, जो आगे आ रहे हैं।

Challenge

+35 XP

String name और "..." लौटाने वाले method String sound() के साथ class Animal लिखें। Dog और Cat, Animal को extend करें और sound() को override करके "Woof" और "Meow" लौटाएँ। main() में एक type (dog/cat) और एक name पढ़ें, फिर print करें: Input: dog Tommy Output: Tommy says Woof

Output Loading Java (first time takes a few seconds)
Press Run to see the result here.