Get immediate access to this and over 1,500+ other videos and books.

Boost your skills with a raywenderlich.com Beginner subscription. With over 60+ video courses and our core foundational programming books bundled in one subscription, it’s simply the best investment you can make in your development career.

Override Methods

This video was last updated on Jun 28 2022

See how to to provide different implementations of methods in child classes.

Contributors

Heads up... You've reached locked video content where the transcript will be shown as obfuscated text.

You can unlock the rest of this video course, and our entire catalogue of books and videos, with a raywenderlich.com Professional subscription.

Often times when you write a subclass, you want to make a change in the way an object behaves. This can result in adding new methods but also, you change existing methods as well. This is known as overriding. When we override a method, you can provide a different implementation of that method. But yet, there are times where we still want to use the original method.

class Teacher {
  
  List<int> grades;
  
  Teacher(this.grades);
  
  int getAverage() {
    int sum = 0;
    for (var grade in grades) {
      sum += grade;
    }
    return sum ~/ grades.length;
  }
}
class StudentTeacher extends Teacher {

}
StudentTeacher(this.grades);
StudentTeacher(super.grades);
@override
int getAverage() => super.getAverage() + 5;
var grades = [68, 80, 96, 37];
var teacher = Teacher(grades);
var studentTeacher = StudentTeacher(grades);
print(teacher.getAverage());
print(studentTeacher.getAverage());

Reviews

Comments