Subclass In Java
Welcome to the Java tutorial post. In our previous post, we discussed inheritance in Java. And in this post, we’re going to discuss subclass.
As we know, in Java, every class is built from another Java class except the object class. Here, the newly created class is called a subclass. You need to remember that A subclass inherits state and behavior from all of its ancestors.
Subclass Definition
A class derived from another class is called a subclass (also a derived class, extended class, or child class). The subclass derived from the class is called a superclass (also a base class or a parent class).
Define Subclass
When you are coming for an interview, you may face technical Java interview questions around the defined subclass. So, we plan to share more detailed information about the Java subclass or subclass Java.
What is a subclass in Java?
When there is a relationship between two objects in Java, there is a name given to the class that inherits the methods and variables of the superclass. That’s why the subclass is a more specialized version of the superclass. The Subclass is also called derived, child, or extended classes.
how to create a subclass in Java
To create a subclass, we need to use the keyword “extends”. Afterward, you must follow the “extends” keyword with the parent class you want to extend.
For Example:
Public class SubClassName extends ParentClassName
Advantages Of Using Subclass
There are several advantages of using Subclass in Java, like:
- Reuse of code: Through inheritance, a subclass can reuse methods that already exist in a superclass.
- Specialization: In a subclass, you can add new methods to handle cases the superclass does not handle. You can also add new data items that the superclass does not need.
- Change in action: A subclass can override a method it inherits from a superclass by defining a method of the same signature as that in the superclass. When you override a method, you might make only a few minor changes or completely change what the method does.
Java Subclass Example
package com.java.Softwaretestingblog; class superclass { public void show() { System.out.println("Parent Class"); } } public class SubclassExample extends superclass{ SubclassExample() { super.show(); } public static void main(String[] args) { // TODO Auto-generated method stub SubclassExample obj=new SubclassExample(); }
Output:
Parent Class