Thursday, May 5, 2011

Published 5/05/2011 by with 2 comments

invalid method declaration; return type required

The Java error "invalid method declaration; return type required" can occur for any of the following reasons:

1. You are trying to define a constructor (of course without any return type; not even void)  but the constructor name is not given same as the class name.

See the wrong code below:

public class Employee
{
 private int id;
 private String name;
 public employee(int id,String name) // constructor name is not same as the class name.
 {
  this.id = id;
  this.name = name;
 }
}


So check the spelling of the constructor name and also note that Java is a case sensitive language.

2. If you are really defining a method (not a constructor) you have forgotten to declare the return type as the wrong code given below:


public class Test
{
public aMethod() // no return type given
{
System.out.println("This is a method");
}
}

The correct code is:


public class Test
{
public void aMethod() // return type void is given now
{
System.out.println("This is a method");
}
}


    email this       edit

2 comments:

  1. import java.util.Date;
    public class Cusstomer{
    private String firstName;
    private String surname;
    private Date dateOfBirth;
    private String status;
    private int bankAccountsHeldByCustomer;
    private String emailAddress;
    private int mobileNumber;
    private Sring idNumber;


    public getFirstName(){
    return firstName;
    }
    public getSurname(){
    return surname;
    }
    public getDateOfBirth(){
    return dateOfBirth;
    }

    ReplyDelete
  2. the above solutions didnt work for this code

    ReplyDelete