3

I was reading this post:

How do I call one constructor from another in Java?

call one constructor from another in java

But I don't know what is the problem whit my code:

NOTE: Only I'm using one call of constructor of three... the error message is indicated like message using // or /*...*/...

class SomeClass {
  private RandomAccessFile RAF = null;

  public SomeClass(String theName) {
    try {
      RandomAccessFile raf = new RandomAccessFile(theName, "r");
      this(raf); //call to this must be first statement in constructor
      SomeClass(raf); /*cannot find symbol
                        symbol:   method SomeClass(RandomAccessFile)
                        location: class SomeClass*/
      this.SomeClass(raf); /*cannot find symbol
                        symbol: method SomeClass(RandomAccessFile)*/
    } catch (IOException e) {}
  }

  public SomeClass(RandomAccessFile RAFSrc) {
    RAF = RAFSrc;

    //...
  }

  //...
}

What's the problem?

Community
  • 1
  • 1

2 Answers2

0

To delegate to the other constructor this must be the first line in the constructor. I would suggest you re-throw IOException from the constructor. Something like,

class SomeClass {
    private RandomAccessFile raf = null;

    public SomeClass(String theName) throws IOException {
        this(new RandomAccessFile(theName, "r"));
    }

    public SomeClass(RandomAccessFile raf) {
        this.raf = raf;
    }
}

Your other option is to duplicate the functionality (if you want to swallow the Exception) like,

public SomeClass(String theName) {
    try {
        this.raf = new RandomAccessFile(theName, "r");
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}

But then you need to deal with raf possibly being null.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

When you call one constructor inside another one, it must be the first instruction.

class SomeClass {
  private RandomAccessFile RAF = null;

  public SomeClass(String theName) {
    this(new RandomAccessFile(theName, "r")); 
  }

  public SomeClass(RandomAccessFile RAFSrc) {
    RAF = RAFSrc;

    //...
  }

  //...
}