-1

So i was writing practicing this java program on inheritance... I created a parent class (Account) and a child class (Savings)... When i tried to run the program it said "There is no default constructor available in com.company.Account" while highlighting the Savings class.

class Account{
   //properties and methods are present here
   public class Account(){ //If I don't write this then the program will not run even though I have set a parameterized Constructor 
   }

   public Account(String acno, String name, String dob, String address){ // Parameterized Constructor
        this.acno=acno;
        this.name=name;
        this.dob=dob;
        this.address=address;
        setBalance(0);
    }
}

class Savings extends Account{ //This portion gets highlighted if I dont write Account() constructor
//Random codes present here
}

When I set the default constructor on Account by myself it shows no error and the program runs smoothly.

Isn't default constructor supposed to be set automatically? Why is there a need to write Account() constructor manually while inheriting?

  • 1
    Because you've written another constructor in the class. The implicit constructor is only added if the class has no explicit constructors. – khelwood Feb 11 '21 at 08:39

1 Answers1

0

A default constructor is built only if you don't specify a specific one for your Object. In your case for your Account class you already have defined a constructor with 4 parameters. When you extend this Account class you have to call the specified constructor of Account class.

You can find similar question here: Java default constructor

D. Mateescu
  • 146
  • 1
  • 10