⬅ Previous Topic
Java enum KeywordNext Topic ⮕
Java final Keywordextends
Keyword⬅ Previous Topic
Java enum KeywordNext Topic ⮕
Java final Keywordextends
Keyword in JavaThe extends
keyword in Java allows one class to inherit the fields and methods of another class. This is Java's way of implementing single inheritance. Inheritance is one of the core pillars of object-oriented programming (OOP), and extends
is the gateway to it.
extends
Do?When one class extends
another, it means the child class (also called the subclass or derived class) gains all the accessible properties and behaviors (methods) of the parent class (also called the superclass).
class ParentClass {
// fields and methods
}
class ChildClass extends ParentClass {
// additional fields and methods
}
class Animal {
void makeSound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
d.makeSound(); // inherited method
d.bark(); // Dog's own method
}
}
Animal makes a sound
Dog barks
In this example, the class Dog
inherits the method makeSound()
from Animal
. It can use both its own methods and the ones from its parent.
class Animal {
void makeSound() {
System.out.println("Generic animal sound");
}
}
class Cat extends Animal {
@Override
void makeSound() {
System.out.println("Meow");
}
}
public class Main {
public static void main(String[] args) {
Animal a = new Cat(); // polymorphism
a.makeSound();
}
}
Meow
The subclass Cat
overrides the makeSound()
method. Even though the reference is of type Animal
, the actual object is Cat
. So, the overridden method in Cat
is executed. This is dynamic method dispatch at play.
class Vehicle {
int speed = 60;
}
class Car extends Vehicle {
String brand = "Toyota";
}
public class Main {
public static void main(String[] args) {
Car car = new Car();
System.out.println(car.speed); // inherited field
System.out.println(car.brand); // Car's own field
}
}
60
Toyota
extends
when there's a clear "is-a" relationship. For example, a Dog
is an Animal
.@Override
to catch mistakes at compile time.implements
keyword.⬅ Previous Topic
Java enum KeywordNext Topic ⮕
Java final KeywordYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.