简体   繁体   中英

“Cannot find symbol symbol : constructor …” in Java?

I have a class defined as follows...

public class df {
    String dt;
    String datestring;

    public String df(String dtstring) throws Exception {
        dt=dtstring;
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date inpdate = formatter.parse(dt);
        datestring = formatter.format(inpdate);
        Date outpdate = formatter.parse(datestring);
        SimpleDateFormat newformatter = new SimpleDateFormat("dd/MM/yyyy");
        datestring = newformatter.format(outpdate);
        return datestring;
    }
}

I create instances of this class as follows, where rsnpos.getString(1) contains a date in yyyy-MM-dd format (eg 2010-01-01)...

new df(rsnpos.getString(1))

During compilation, I am getting the following error...

cannot find symbol
symbol  : constructor df(java.lang.String)
location: class df

I don't understand why this is happening, as I have defined a constructor as shown in my code. Could someone please assist me with this problem.

public class df
     {
 String dt;
 String datestring;
 public df(String dtstring) throws Exception
        {
                dt=dtstring;
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                Date inpdate = formatter.parse(dt);
                datestring = formatter.format(inpdate);
                Date outpdate = formatter.parse(datestring);
                SimpleDateFormat newformatter = new SimpleDateFormat("dd/MM/yyyy");
                datestring = newformatter.format(outpdate);
        }
    }

See http://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html .

That's not a constructor... (constructors have an implicit "return type", the type of the class). That has an explicit return type, and is thus not a constructor, but a normal method named df .

Thus it is invalid when used as new df(...) , which is exactly what the error message says. On the other hand, new df().df("x") would still "work" because of the default parameterless constructor and the method String df(String) .

Note the updates to change it into a constructor:

public class df 
{

  String dt;
  String datestring;
  // Remove return type (and keep matched name) to make it a constructor.
  public df(String dtstring) throws Exception
  {
    dt=dtstring;
    ...
    datestring = newformatter.format(outpdate);
    // Constructors cannot "return"
    // return datestring;
  }

}

Please work on variable names and naming conventions and mutability redux :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM