extends (Web Development)
Learn extends (Web Development) step by step with clear examples and exercises.
Title: Extends Keyword in Java - A full guide
Why This Matters
In this tutorial, we will delve into the extends keyword in Java, a fundamental concept that enables inheritance and code reusability. Understanding extends is crucial for writing efficient, scalable, and maintainable code during exams, interviews, or real-world projects.
Prerequisites
To make the most of this tutorial, you should have a good understanding of Java syntax, variables, methods, and basic classes. Familiarity with object-oriented programming principles is also beneficial.
Core Concept
Understanding Inheritance
Inheritance is a mechanism that allows one class (the subclass or derived class) to acquire the properties of another class (the superclass or base class). The extends keyword in Java is used to establish inheritance relationships between classes.
Syntax and Basic Usage
To create a subclass, we write a new class that extends a superclass using the extends keyword followed by the name of the superclass. Here's an example:
public class SuperClass {
// properties and methods of the superclass
}
public class SubClass extends SuperClass {
// properties and methods specific to the subclass
}
In this example, SubClass inherits all the properties and methods from SuperClass. We can access these inherited members using their original names in the subclass.
Overriding Methods
One of the key benefits of inheritance is the ability to override methods in a subclass. To do this, we create a method with the same name, return type, and parameters as the overridden method in the superclass. The @Override annotation can be used to ensure that a method correctly overrides a method from the superclass.
public class SuperClass {
public void printMessage() {
System.out.println("Hello from SuperClass");
}
}
public class SubClass extends SuperClass {
@Override
public void printMessage() {
System.out.println("Hello from SubClass");
}
}
In this example, the printMessage() method in SubClass overrides the same method in SuperClass. When we call printMessage() on an instance of SubClass, it will print "Hello from SubClass" instead of the default message.
Accessing Members from the Superclass
We can access members (properties and methods) of the superclass using one of three ways:
- Directly, if they are public or protected in the superclass.
- Using
superkeyword, which allows us to call a method or access a property that is overridden in the subclass. - Through inheritance hierarchy, by calling methods on an instance of the superclass if it's available (e.g., when a subclass inherits from another subclass).
Constructors and Inheritance
When we create a subclass using extends, the subclass constructor is automatically called after the superclass constructor. We can call the superclass constructor explicitly using super() in the subclass constructor. If no explicit constructor call is made, the default no-argument constructor of the superclass is called.
public class SuperClass {
public SuperClass() {
System.out.println("Constructing SuperClass");
}
}
public class SubClass extends SuperClass {
public SubClass() {
super(); // calls the constructor of SuperClass
System.out.println("Constructing SubClass");
}
}
In this example, when we create an instance of SubClass, it will first construct SuperClass and then construct SubClass.
Worked Example
Let's create a simple hierarchy of classes representing different shapes. We have a Shape superclass with properties for the shape's name and area, and two subclasses Circle and Rectangle that inherit these properties and provide their own implementations for calculating the area.
public class Shape {
private String name;
private double area;
public Shape(String name) {
this.name = name;
}
public void setArea(double area) {
this.area = area;
}
public double getArea() {
return area;
}
@Override
public String toString() {
return "Shape [name=" + name + ", area=" + area + "]";
}
}
public class Circle extends Shape {
private final double radius;
public Circle(String name, double radius) {
super(name);
this.radius = radius;
setArea(Math.PI * Math.pow(radius, 2));
}
@Override
public String toString() {
return "Circle [name=" + name + ", radius=" + radius + ", area=" + getArea() + "]";
}
}
public class Rectangle extends Shape {
private final double length;
private final double width;
public Rectangle(String name, double length, double width) {
super(name);
this.length = length;
this.width = width;
setArea(length * width);
}
@Override
public String toString() {
return "Rectangle [name=" + name + ", length=" + length + ", width=" + width + ", area=" + getArea() + "]";
}
}
In this example, we have a Shape superclass with two subclasses Circle and Rectangle. Both subclasses inherit the properties and methods from Shape, and each provides its own implementation for calculating the area. We can create instances of these classes and print their details as follows:
public class Main {
public static void main(String[] args) {
Shape circle = new Circle("Circle", 5);
System.out.println(circle);
Shape rectangle = new Rectangle("Rectangle", 4, 6);
System.out.println(rectangle);
}
}
In this example, we create instances of Circle and Rectangle, which inherit from Shape. We print the details of both shapes using their toString() methods.
Common Mistakes
- Forgetting to call super() in a subclass constructor: If we forget to call
super()in the subclass constructor, the default no-argument constructor of the superclass will not be called, and the subclass instance may not have all its properties initialized correctly. - Not overriding methods when necessary: Sometimes, we might need to override a method in the subclass but forget to do so. This can lead to unexpected behavior or incorrect results.
- Using
thisinstead ofsuperfor accessing members from the superclass: When we want to call a method or access a property that is overridden in the subclass, it's important to usesuperinstead ofthis. Usingthiswill call the overridden method in the subclass, not the original method in the superclass. - Creating redundant subclasses: In some cases, we might create a new subclass that inherits from an existing subclass without adding any new functionality or properties. This can lead to unnecessary complexity and make the code harder to maintain.
- Incorrectly overriding final methods: Final methods in Java cannot be overridden. If we try to override a final method, it will result in a compile-time error.
Practice Questions
- Create a hierarchy of classes representing different animals with properties for the name, weight, and sound. Inheritance should be used to create subclasses for mammals, birds, and reptiles, each with their own properties and methods specific to the animal group.
- Override the
toString()method in theAnimalsuperclass so that it includes the name, weight, and sound of the animal. - Create a subclass
Dogthat inherits from theMammalclass and provides its own implementation for calculating the weight based on age and breed. - Create a subclass
Eaglethat inherits from theBirdclass and overrides the sound method to play a unique eagle call. - Create a subclass
Crocodilethat inherits from theReptileclass and provides its own implementation for calculating the weight based on length and species.
FAQ
- Can I inherit from multiple classes in Java?
- No, Java does not support multiple inheritance directly. However, we can achieve similar functionality using interfaces or composition.
- What is the difference between
extendsandimplementsin Java?
extendsis used for inheritance, whileimplementsis used to implement an interface.
- Can I call a constructor from a method in Java?
- No, constructors can only be called within the class they are defined or as part of the constructor chain (using
super()).
- What happens if I don't call any constructor in a class with no default constructor?
- If there is no default constructor (no-argument constructor) and we don't provide an explicit constructor call, it will result in a compile-time error.
- Can I override a final method in Java?
- No, final methods cannot be overridden because they are marked as unchangeable by the programmer or the class designer.