Lesson 28 of 34

Inheritance: extends மற்றும் superInheritance: extends and super

10 min 35 XP

extends மூலம் ஒரு class (child) இன்னொரு class-ன் (parent) fields, methods-ஐப் பெறும். super(...) parent constructor-ஐ அழைக்கும். Child, parent-ன் method-ஐ override செய்து தன் சொந்த முறையில் செய்யலாம்.

With extends, a child class inherits the parent's fields and methods. super(...) calls the parent constructor. The child can override a parent method to do it its own way.

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-ஐ மட்டுமே extends செய்ய முடியும் (multiple inheritance இல்லை). அதற்கு interfaces பயன்படும், அடுத்த பாடம்.

A Java class can extend only one class (no multiple inheritance of classes). Interfaces solve that, coming next.

Challenge

+35 XP

Animal class-ல் String name மற்றும் String sound() method ("..." தரும்). Dog மற்றும் Cat, Animal-ஐ extends செய்து sound()-ஐ override செய்ய வேண்டும் ("Woof", "Meow"). main()-ல் type (dog/cat) மற்றும் name படித்து இப்படி print செய்யுங்கள்: Input: dog Tommy Output: Tommy says Woof

Write class Animal with a String name and a method String sound() returning "...". Dog and Cat extend Animal and override sound() to return "Woof" and "Meow". In main(), read a type (dog/cat) and a name, then print: Input: dog Tommy Output: Tommy says Woof

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