Today you will learn:
extends keywordsuper keywordBy the end, you will be able to create class hierarchies and use polymorphism effectively.
Use extends to create a subclass from a base class.
class Animal {
void makeSound() {
System.out.println("Animal sound");
}
}
class Dog extends Animal {
void makeSound() {
System.out.println("Woof");
}
}
Explanation:
Dog is a subclass of AnimalA subclass can provide its own implementation of a method.
class Dog extends Animal {
void makeSound() {
System.out.println("Woof");
}
}
Explanation:
Dog class overrides makeSound()Dog objectsuper refers to the parent class and can be used to call parent methods or constructors.
class Dog extends Animal {
void makeSound() {
super.makeSound(); // calls Animal's makeSound
System.out.println("Woof");
}
}
Polymorphism allows a parent reference to point to a child object.
Animal myAnimal = new Dog();
myAnimal.makeSound(); // Prints "Woof"
Explanation:
class Animal {
void makeSound() {
System.out.println("Animal sound");
}
}
class Dog extends Animal {
void makeSound() {
System.out.println("Woof");
}
}
Create a base class Shape and subclasses Circle and Rectangle with overridden methods.
Steps:
Shape class with a method draw()Circle and Rectangledraw() method in each subclassdraw()Example:
class Shape {
void draw() {
System.out.println("Drawing a shape");
}
}
class Circle extends Shape {
void draw() {
System.out.println("Drawing a circle");
}
}
class Rectangle extends Shape {
void draw() {
System.out.println("Drawing a rectangle");
}
}
public class Main {
public static void main(String[] args) {
Shape shape1 = new Circle();
Shape shape2 = new Rectangle();
shape1.draw(); // Drawing a circle
shape2.draw(); // Drawing a rectangle
}
}