Extending a class
Description
A child class inherits from one parent class.
Explanation
Use inheritance only for a genuine is-a relationship.
Example
class GraduateStudent extends Student { }← Chapter 6 — Object-Oriented Programming
mixed
Inheritance lets one class reuse and extend another class. A child class uses extends to inherit accessible fields and methods from its parent.
The super keyword refers to the parent part of the current object. Use it to call a parent constructor or deliberately reuse a parent method.
A child class inherits from one parent class.
Use inheritance only for a genuine is-a relationship.
class GraduateStudent extends Student { }super can call the parent constructor.
It must be the first statement in a child constructor.
super(name);Java supports single class inheritance: a class has one direct parent. It can still implement multiple interfaces, which often provides a flexible alternative.
public class InheritanceDemo {
static class Student {
String name;
Student(String name) { this.name = name; }
}
static class GraduateStudent extends Student {
GraduateStudent(String name) { super(name); }
}
public static void main(String[] args) {
System.out.println(new GraduateStudent("Rohan").name);
}
}