0

i'm trying to create a method that adds a certain object into an array of inherited objects.

public class Biblio {
Biblio[] Tab; static int i=0;
Biblio();
void insert(Biblio O){Tab[i]=O;i++;}}     

in the main class, i created 3 objects of classes that extend from each others: means Document extends from Biblio, Article extends from Document, Book extends from Article.

public class TestBiblio {
public static void main(String[] args) {
    Document A= new Document();
    Article B= new Article();
    Book C= new Book();
    Biblio D= new Biblio();
    D.insert(A);
    D.insert(B);
    D.insert(C);}}

Once i run the code, i get Exception in thread "main" java.lang.NullPointerException error. i'm a beginner in java, i couldn't find out hat went wrong..

3
  • 2
    you should do something like: Biblio[] Tab = new Biblio[specify_count]; and your constructor doesn't has a body Commented Dec 3, 2014 at 19:04
  • can you post the full stack trace? Are all classes in the same package/folder? Commented Dec 3, 2014 at 19:05
  • yes it worked, i had to add Tab = new Biblio[5]; in the constructor. Commented Dec 8, 2014 at 12:54

1 Answer 1

4

You never initialized the array that you used to insert. When you do Tab[i], you are dereferencing a null pointer. Have something like

    public class Biblio {
           Biblio[] Tab; 
           static int i=0;
           public Biblio() {
                  Tab = new Biblio[5];
           }
          void insert(Biblio O){
                 Tab[i]=O;i++;
           }
      }     
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.