extends
- Java course
- Intermediate
- Lesson 13/116
- 5 min
Learn inheritance with extends.
The extends keyword
Inheritance lets a class inherit fields and methods from another class. In Java it is done with the extends keyword. The inheriting class is called a subclass, the inherited class a superclass.
Example: class Dog extends Animal { }. Here Dog is the subclass, Animal the superclass. Dog accesses all public and protected fields and methods of Animal. Inheritance reduces code duplication; shared features stay in the superclass, subclasses specialize.
Inherited members
A subclass directly accesses the public and protected members of its superclass. It can use them without redefining them. private members are not directly accessible; they are reached through getters and setters.
Example: Suppose Animal has String name and void eat(). When you write Dog extends Animal, a Dog instance can call d.name and d.eat(). These members do not need to be rewritten inside Dog. Inheritance keeps code in one place and eases reuse.
Practice Make Dog inherit from Animal
Define a class Animal with a String name field and a void eat() method. The method body writes System.out.println(name + " eats");. Then define Dog extends Animal with a void bark() method whose body writes System.out.println(name + " barks");. Put main inside Dog; create a Dog instance, assign name, call eat and bark.
Starter code
// Define the Animal class
// Define Dog extends Animal
// Instantiate and call in mainSample solution
class Animal {
String name;
void eat() {
System.out.println(name + " eats");
}
}
class Dog extends Animal {
void bark() {
System.out.println(name + " barks");
}
public static void main(String[] args) {
Dog d = new Dog();
d.name = "Rex";
d.eat();
d.bark();
}
}Expected output
Rex eats Rex barks
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which is an inheritance definition?
- class Dog : Animal { }
- class Dog implements Animal { }
- class Dog from Animal { }
- class Dog extends Animal { } Correct answer
Explanation: The extends keyword establishes the inheritance relationship.
2 Complete the inheritance definition
class Dog ____ Animal {
void bark() { }
}
class Dog extends Animal {
void bark() { }
}
Explanation: The extends keyword establishes inheritance.
3 Match the inheritance parts
| Term | Meaning |
|---|---|
extends |
Inheritance keyword |
Dog |
Subclass |
Animal |
Superclass |
name |
Inherited field |