CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Jul 2012
    Posts
    1

    Constructor not being called

    I was asked to explain why the line
    Code:
    System.out.println("" + x[2].getN());
    wont work. I figure the constructor is not being triggered but the why, beats me. Anyone care to explain?

    Code:
    class Num{ 
        private int n; 
        public int getN(){ return n;} 
        public Num( ){ n = 4; } 
    } 
    public class Main { 
      public static void main( String[] args){ 
        Num [] x = new Num[7]; 
        System.out.println("" + x.length);  
        System.out.println("" + x[2].getN());               
      } 
    }

  2. #2
    Join Date
    Jan 2012
    Posts
    17

    Re: Constructor not being called

    If I'm not mistaken you're probably getting a NullPointerException?

    You've shown that Num holds an array of Num objects but you haven't assigned a Num object to the array
    Try
    Code:
     Num [] x = new Num[7] ;
    int i = 0 ;
        while(i < 7)
        {
            x[i] = new Num() ;
            i++ ;
        }
    this should call the empty constructor of the object Num to the array and create the object of it.
    The "=" the assigns the object to your array. Use a loop then for the rest of the elements. The line should work then!

    Sorry if this confuses you it's the first time I've provided advice and it's the best I can explain it to you :-)

  3. #3
    Join Date
    Nov 2006
    Location
    Barcelona - Catalonia
    Posts
    364

    Re: Constructor not being called

    I think you made a perfect explanation.

    Expression
    Code:
    Num [] x = new Num[7]
    only tells de JVM to allocate a block of contiguous memory. Num constructor is NOT called.

    Albert.
    Please, correct me. I'm just learning.... and sorry for my english :-)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured