0

I have to do this program with a superclass called Document and two subclasses (DVD and book). Basically the two subclasses inherit the attributes of Document + one or two specific attributes for each.

This is my superclass:

public class Document {

    public String nom;
    public int copiesDispo;
    public String noRef;

    public static int nbDocs;

    /*
    ** Constructor(s)
    */

    public Document(String nom, String noRef) {

        this.nom = nom;
        this.noRef = noRef;
        this.copiesDispo = copiesDispo;

        nbDocs++;

    }

}

And here is what I have so far for the subclass book:

public class Livre extends Document {
    
     public Livre() {
        
        super();
        
    }
    
}

This doesn't compile though, it seems like I can't do that but I have done this before in a previous program and had no problem..? What's the issue here/why? Does it mean I have to make the superclass abstract?

Stephen P
  • 14,422
  • 2
  • 43
  • 67
manouna
  • 93
  • 1
  • 8
  • 1
    You'll need to add an empty constructor to Document if calling its constructor with no arguments. – Randy Casburn Apr 09 '21 at 22:00
  • Does this help you https://stackoverflow.com/questions/9586367/constructor-of-subclass-in-java ? – dreamcrash Apr 09 '21 at 22:02
  • 1
    `copiesDispo` is unknown in the constructor of `Document`; note that you don't pass it as a parameter, like you do with the other two. – Jesper Apr 09 '21 at 22:06
  • @Jesper I should pass it as a parameter as well? – manouna Apr 10 '21 at 18:49
  • Yes, otherwise `this.copiesDispo = copiesDispo;` won't do anything useful; you probably want to set `copiesDispo` also according to a parameter. – Jesper Apr 10 '21 at 19:07

1 Answers1

0

super() will in fact call the actual constructor of your superclass

Here, you're hiding the default constructor (without arguments) because you have added one in the super class with arguments

You can take a look at the JLS

You basically have two choices

  • Add a default constructor public Document() { } to your superclass
  • Invoke the constructor with default arguments in your subclasses (less preferred option)
Yassin Hajaj
  • 21,337
  • 9
  • 51
  • 89
  • but if I use a default constructor, how will the values be assigned since they are declared with no value here? – manouna Apr 10 '21 at 18:50