Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing

Learn Dart inheritance

Inheritance is a fundamental concept in object-oriented programming that allows a class (subclass or derived class) to inherit properties and behaviors from another class (superclass or base class). Dart supports single inheritance, meaning a subclass can inherit from only one superclass. Let's explore how inheritance works in Dart:



Syntax
In Dart, you use the extends keyword to indicate that a class is inheriting from another class. The subclass inherits all the members (fields, methods, getters, setters) of the superclass.

class SuperClass {
// Superclass members
}
class SubClass extends SuperClass {
// Subclass members
}


Constructor Inheritance:
When a subclass is created, the superclass constructor is automatically called. If the superclass has a constructor that takes arguments, the subclass must call it using the super keyword in its own constructor.

class Animal {
String name;
Animal(this.name);
} class Dog extends Animal {
String breed;
Dog(String name, this.breed) : super(name);
}


Overriding Methods:
A subclass can provide its own implementation for a method defined in the superclass. This is known as method overriding. You use the @override annotation to indicate that a method is overriding a superclass method.

class Animal {
void speak() {
print('Animal speaks');
}
}
class Dog extends Animal {
@override
void speak() {
print('Dog barks');
}
}


Accessing Superclass Members:

You can access superclass members (fields, methods) from the subclass using the super keyword.

class Animal {
void speak() {
print('Animal speaks');
}
}
class Dog extends Animal {
@override
void speak() {
super.speak(); // Call superclass method
print('Dog barks');
}
}





Advertisement





Q3 Schools : India


Online Complier

HTML 5

Python

java

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

java