Sharon Watinsan
Sharon Watinsan

Reputation: 9850

Not allowed to include a default constructor - Java Basics

Class A:

public class A {    

    private String firstName;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

Class B:

public class B extends A{

    private int billNum;

    B(String firstName, String billNum) {
        super(firstName);
        setBillNum(billNum);

    }

    public int getBillNumr() {
        return billNum;
    }

    public void setBillNum(int billNum) {
        this.billNum = billNum;
    }

1.) Now i want to add a default like constructor like B() {}, but i am not allowed to do so. Why is this ?

Upvotes: 1

Views: 135

Answers (3)

PermGenError
PermGenError

Reputation: 46428

Firstly you don't have an constructor in class a which takes a string as an argument and you are trying to call super(first name) from ur subclass constructor.

class A{
String firstName;
public aA(String firstname){
this.firstName= firstName;
}
}

Upvotes: 1

Marko Topolnik
Marko Topolnik

Reputation: 200166

In the subclass constructor you call a one-argument superclass constructor, which you didn't declare. Add A(String firstName) { this.firstName = firstName; } to the superclass. Alternatively, replace the line super(firstName); with setFirstName(firstName); in the constructor of B.

Upvotes: 4

Jon Skeet
Jon Skeet

Reputation: 1501163

The code you've provided won't compile, due to this line in B:

super(firstName);

That suggests that actually, your A class has a constructor like this:

public A(String firstName) {
    this.firstName = firstName;
}

At that point, trying to declare a new constructor in B will fail without a super call, because there isn't a parameterless constructor in A.

So this will work:

B() {
  super("Anonymous");
}

Or you could add a parameterless constructor to A:

A() {
  this("Anonymous");
}

... at which point you can just use B() {} in B.

Basically, once you understand that a constructor without any explicit this(...) or super(...) call is equivalent to calling super() (i.e. a parameterless constructor in the superclass) it all makes sense.

Upvotes: 9

Related Questions