Reputation: 59
I had extended a class called Account from a class Interest
import java.util.*;
import java.io.*;
public class Interest extends Account{
public static void main(String args[]){
Scanner scan = new Scanner(System.in);
int id = scan.nextInt();
double balance = scan.nextDouble();
double rate = scan.nextDouble();
int noOfYears = scan.nextInt();
Account acc = new Account(id,balance,rate);
double interest = calculateInterest(acc,noOfYears);
System.out.println(interest);
//System.out.println("%.3f",calculateInterest(acc,noOfYears));
}
public static double calculateInterest(Account acc, int noOfYears){
return( acc.rate);
}
}
class Account{
int id;
double balance;
double rate;
public Account(int id, double balance, double rate){
this.id = id;
this.balance = balance;
this.rate = rate;
}
public int getId(){return id;}
public double getBalance(){return balance;}
public double getInterestRate(){return rate;}
}
I got an error as
Interest.java:4: error: constructor Account in class Account cannot be applied to given types; class Interest extends Account{ ^ required: int,double,double found: no arguments reason: actual and formal argument lists differ in length 1 error
Upvotes: 0
Views: 263
Reputation: 401
Because a subclass's constructor also needs to invoke its parent class's constructor. Since your class Account doesn't have a default constructor because you explicitly provide a constructor, compiler can't instantiate a default super()
for you. You need to declare a constructor for Interest that looks like this
public Interest(int id, double balance, double rate) {
super(id, balance, rate);
...
...
}
And you might need to double check what you wanna do here. You aren't actually instantiating an Interest object at all in your code. It should be something like
Account acc = new Interest(id,balance,rate);
Upvotes: 3