B-Mac
B-Mac

Reputation: 567

Error in extending an abstract class

I was just experimenting with abstract classes and bumped into an error.

I have one class as:

public abstract class C {
    String aname;
    int aid;

    public C(String s, int n) {
        aname = s;
        aid = n;
    }

    public static void main(String[] args) {
        System.out.println("Hello");
    }
}

Now, another class extends it as follows:

public class D extends C {

    public static void main(String[] args) {

    }
}

However, it gives the following error:

error: constructor C in class C cannot be applied to given types;
public class D extends C {
       ^
  required: String,int
  found: no arguments
  reason: actual and formal argument lists differ in length

Upvotes: 1

Views: 852

Answers (3)

Aninda Bhattacharyya
Aninda Bhattacharyya

Reputation: 1251

You have a parameterized constructor only in the abstract class. Try to have explicit default constructor or override the one in child.

Upvotes: 0

rgettman
rgettman

Reputation: 178343

This has nothing to do with abstract classes and methods, and everything to do with the fact that you don't have a constructor declared in D.

You have only one constructor in C, and it takes 2 arguments. You did not declare a constructor in D, so Java implicitly inserts a no-arg, default constructor. It calls the superclass's default (no-arg) constructor, but that doesn't exist in C.

You must explicitly create a D constructor that calls C's 2-arg constructor or supply a no-arg constructor in C.

Upvotes: 0

M A
M A

Reputation: 72884

Since class D does not define any constructor, the compiler automatically creates a default no-argument constructor for it. However, this constructor implicitly calls the no-argument constructor of the base class C, which is not defined -- a no-argument constructor exists if you explicitly define one or if you don't define any constructor. To solve it, you can either define a no-arg constructor for C:

public C() {

}

or you can define a constructor in D that has the same parameters as that of the parent class:

public D(String s, int n) {
    super(s, n);
}

Upvotes: 1

Related Questions