Alan
Alan

Reputation: 2129

Getting strange java.lang.NoSuchMethodError error

I have an interface called Namable

public interface Namable { public String getName(); public void setName(String name); };

Several classes will implement this.

When I make code like this:

Namable foo = new X(); foo.getName();

(X is an implementing class)

I get the error:

java.lang.NoSuchMethodError: Namable.getName()Ljava/lang/String;

This is very strange to me and I'm wondering why this is happening, any thoughts?

Compilable example:

Namable class:

public interface Namable 
  {
    public String getName();
  }

Extending class X:

public class X extends java.util.ArrayList implements Namable 
{
  private String name;
  public X() 
  {
    this.name = "bar";
  }
  public String getName() 
  {
    return name;
  }
}

Testing class:

public class Test 
{
  public static void main() 
  {
    Namable foo = new X();
    foo.getName();
  }
}

After running this, I get the same error. I am using BlueJ

Upvotes: 0

Views: 2948

Answers (4)

DNA
DNA

Reputation: 42597

You need to call

foo.getName()

not

X.getName()

You are trying to call a class (static) method that doesn't exist.

And it should be Namable foo = new X(); - your example code shouldn't even compile as shown.

Can you provide a SSCCE ?

Updated following corrections and SSCCE: Just a wild guess now, but does BlueJ define a Namable already, or do you have a Namable in another package that might be imported instead? What happens if you rename Namable to Namable2 throughout, in the example above?

Upvotes: 2

J Barclay
J Barclay

Reputation: 491

I have run an example with the classes you have given here and it works as expected once the main method is changed to:

public static void main(String[] args)

However, as you are using BlueJ this may not be a problem (I remember BlueJ using a special mechanism to run classes).

Do you have another class Nameable in your classpath? Check the package import and make sure it is the interface you have defined. It appears the error is with your environment and not with the code.

Upvotes: 3

RanRag
RanRag

Reputation: 49567

When I ran your code snippet, the error shown is

Error: Main method not found in class Test, please define the main method as: public static void main(String[] args)

Change your main method to

public static void main(String[] args)

I am not getting

java.lang.NoSuchMethodError: Namable.getName()Ljava/lang/String;

with your given code snippet.

Upvotes: 0

HammerGuy
HammerGuy

Reputation: 101

As stated by DNA your post would be better with a SSCCE

My guess would be that maybe you could have missed a "static" keyword in main function

public static void main(String args[]) 

not

public void main(String args[]) 

Could be something a classpath problem too... Or a file name and class mismatch. Or something else.

Upvotes: 0

Related Questions