-5

I need to create a class for the methods described in the interface as follows:

public interface MyStringInterface {

    // Sets the value of the current string
    public void setString(String str);

    // Returns the current string
    public String getString();
}

When I create a class with methods as below, there is always this error and wont let me proceed. What am I doing wrong? How should I proceed?

package seclass.assgn;

public class MyString implements MyStringInterface{

    static String name;

    public static void main(String[] args) {            
        setString("This is my sentence");
        System.out.println(getString());
    }

    public void setString(String str){
        name = str;
    }
    public String getString() {
        return name;
    }
}
takendarkk
  • 3,347
  • 8
  • 25
  • 37
javabeginner
  • 91
  • 3
  • 11

2 Answers2

1

You need an instance of MyString -

public static void main(String[] args) {
  MyString my = new MyString();            
  my.setString("This is my sentence");
  System.out.println(my.getString());
}

also

static String name;

should be

private String name;

Alternatively, if you don't want an instance just use

public static void main(String[] args) {
  name = "This is my sentence";
  System.out.println(name);
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
1

First of all, you don't have to repeat "public" in interfaces.

public interface MyStringInterface {
    void   setString(String str);
    String getString();
} // end of class MyStringInterface

Then you must make an Object of your implementation:

public class MyString implements MyStringInterface {
String name;

public static void main(String[] args) {
    new MyString().top();
}


void top() {
    setString("This is my sentence.");
    System.out.println(getString());
}


@Override
public void setString(String str) {
    this.name = str;
}


@Override
public String getString() {
    return this.name;
}

} // end of class MyString
takendarkk
  • 3,347
  • 8
  • 25
  • 37
iGeeks
  • 192
  • 1
  • 11
  • Good! +1 for correct answer and for mentioning to not use the `public` keyword for interface members. – Seelenvirtuose Sep 02 '14 at 06:00
  • Even better would be, to separate the test-program from the implementation. But I think, that was not the question. – iGeeks Sep 02 '14 at 08:03