You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Inheritance lets you create new classes based on existing ones, reusing and extending their behaviour. Polymorphism means a single interface can represent different underlying forms. Together, they are two of the four pillars of object-oriented programming.
extendsA subclass (child) inherits fields and methods from a superclass (parent):
public class Animal {
String name;
public Animal(String name) {
this.name = name;
}
public void speak() {
System.out.println(name + " makes a sound");
}
}
public class Dog extends Animal {
public Dog(String name) {
super(name); // call the parent constructor
}
@Override
public void speak() {
System.out.println(name + " barks");
}
}
| Rule | Detail |
|---|---|
| Single inheritance only | A class can extend exactly one parent class |
super() | Calls the parent constructor — must be the first statement |
@Override | Annotation indicating a method overrides a parent method |
All classes extend Object | If no extends is specified, the class implicitly extends java.lang.Object |
super KeywordSubscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.