Search⌘ K
AI Features

Inheritance in Java

Explore inheritance in Java to understand how a subclass derives from a superclass, inheriting fields and methods. Learn the use of extends and super keywords to build related classes, and grasp access specifiers and restrictions to write effective object-oriented code.

What is inheritance?

Inheritance provides a way to create a new class from an existing class. The new class is a specialized version of the existing class such that it inherits elements of the existing class.

Terminology

  • Superclass(Parent Class): This class allows the re-use of its members in another class.
  • Derived Class(Child Class or Subclass): This class is the one that inherits from the superclass.

Hence, we can see that classes can be built by using previously created classes!

Notation

Let’s take a look at the notation necessary for the creation of subclasses. This is done by using the keyword extends.

Java
class Student{
public String name;
public int age;
}
class Undergrad extends Student{
String major;
public Undergrad(){
this.major = "Computer"
this.name="John Doe";
this.age=50;
}
}
...