Thursday, May 5, 2011

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");
}
}



If the above solutions do not work for you. Please comment below giving your code. I'll try to respond.

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