Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Inheritance Example

Tags:

java

Below is the example for Inheritance

class Parent {
    Parent(int a, int b) {
        int c = a + b;
        System.out.println("Sum=" + c);
    }
    void display() {
        System.out.println("Return Statement");
    }
}
class Child extends Parent {
    Child(int a, int b) {
        int c = a - b;
        System.out.println("Difference=" + c);
    }
}
public class InheritanceExample {
    public static void main(String args[]) {
        Child c = new Child(2, 1);
        c.display();
    }
}

I get the below error when I don't have the non-parametrized constructor parent()

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
    Implicit super constructor Parent() is undefined. Must explicitly invoke another constructor

    at Child.<init>(InheritanceExample.java:14)
    at InheritanceExample.main(InheritanceExample.java:22)

Can you please explain me what is the purpose of the constructor without parameters in base class.

like image 673
Santosh V M Avatar asked Mar 20 '26 05:03

Santosh V M


1 Answers

class child extends parent
{
    child(int a,int b)
    {
        int c=a-b;
        System.out.println("Difference="+c);
    }
}

The first thing the child class constructor must do is call the parent class constructor. If you do not do this explicitly (e.g. super(a,b)), a call to the default constructor is implied (super()).

For this to work, you must have this default constructor (without any parameters).

If you do not declare any constructors, you get the default constructor. If you declare at least one constructor, you do not get the default constructor automatically, but you can add it again.

The error message you are getting is complaining about the implied call to super() not working, because there is no such constructor in the parent class.

Two ways to fix it:

  1. add a default constructor
  2. in the first line of the child constructor, call a non-default parent constructor (super(a,b))

Also, please don't use all-lowercase class names.

like image 128
Thilo Avatar answered Mar 21 '26 19:03

Thilo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!