Questions And Answers

More Tutorials

Java Inheritance

You might have heard people saying your nose is similar to your father or mother. Or, more formally, we can say that you've inherited the genes from your parents due to which you look similar to them.

The same phenomenon of inheritance is also valid in programming.

In Java, one class can easily inherit the attributes and methods from some other class. This mechanism of acquiring objects and properties from some other class is known as inheritance in Java.

Inheritance is used to borrow properties & methods from an existing class.
Inheritance helps us create classes based on existing classes, which increases the code's reusability.
Examples :

Important terminologies used in Inheritance :

1. Parent class/superclass: The class from which a class inherits methods and attributes is known as parent class.
2. Child class/sub-class: The class that inherits some other class's methods and attributes is known as child class.

Extends keyword in inheritance :

The extends keyword is used to inherit a subclass from a superclass.
Syntax :

class Subclass-name extends Superclass-name  
   //methods and fields  

Example :

public class dog extends Animal { 
     // code 



class Base{
    public int x;

    public int getX() {
        return x;

    public void setX(int x) {
        System.out.println("I am in base and setting x now");
        this.x = x;

    public void printMe(){
        System.out.println("I am a constructor");

class Derived extends Base{
    public int y;

    public int getY() {
        return y;

    public void setY(int y) {
        this.y = y;

public class inheritance {
    public static void main(String[] args) {
        // Creating an Object of base class
        Base b = new Base();

        // Creating an object of derived class
        Derived d = new Derived();


In this page (written and validated by ) you learned about Java Inheritance . What's Next? If you are interested in completing Java tutorial, your next topic will be learning about: Java Constructors in Inheritance.

Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue:

Share On:

Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using, you agree to have read and accepted our terms of use, cookies and privacy policy.