Inheritance, Interfaces and Polymorphism
💻 JavaShare behaviour through inheritance and define contracts with interfaces.
Inheritance reuses a parent class. Interfaces describe what a class can do without saying how. Polymorphism lets one type stand in for many.
- Extend a class.
- Implement an interface.
- Use polymorphism in a list.
Inheritance
A subclass extends a parent and can override methods. Use super to call the parent constructor.
class Animal {
protected String name;
Animal(String name) {
this.name = name;
}
String sound() {
return "...";
}
}
class Dog extends Animal {
Dog(String name) {
super(name);
}
@Override
String sound() {
return "Woof";
}
}Interfaces
An interface lists methods a class must provide. A class can implement several interfaces, which avoids the single-parent limit of inheritance.
interface Gradable {
String grade();
}
class Assignment implements Gradable {
private int score;
Assignment(int score) {
this.score = score;
}
public String grade() {
return score >= 50 ? "Pass" : "Fail";
}
}Polymorphism
A variable typed as the parent or interface can hold any implementing object. The correct override runs at runtime.
Animal[] animals = { new Dog("Rex"), new Animal("Unknown") };
for (Animal animal : animals) {
System.out.println(animal.name + ": " + animal.sound());
}Practice
- Create a Shape parent with an area method.
- Add Circle and Rectangle subclasses.
- Define a Drawable interface and implement it in two classes.
Hands-on exercise
Create an interface Shape with area().
Implement Circle and Rectangle.
Put both in a Shape array and print each area rounded to two decimals.
Recap
Inheritance shares code, interfaces define contracts and polymorphism lets one type handle many implementations.
Example
class Animal {
protected String name;
Animal(String name) {
this.name = name;
}
String sound() {
return "...";
}
}
class Dog extends Animal {
Dog(String name) {
super(name);
}
@Override
String sound() {
return "Woof";
}
}
Exercises
Implement Circle and Rectangle.
Put both in a Shape array and print each area rounded to two decimals.
Expected Output
28.27
20.00
Lesson Nav
Java Course
0/9 lessons completed
- 1 Getting Started with Java Tutorial
- 2 Variables and Data Types Tutorial
- 3 Conditions and Loops Tutorial
- 4 Methods and Parameters Tutorial
- 5 Arrays and ArrayLists Tutorial
- 6 Classes and Objects Tutorial
- 7 Inheritance, Interfaces and Polymorphism Tutorial
- 8 Exceptions and Files Tutorial
- 9 Project: A Console Grade Book Project