Write an interface named Nameable that specifies the following methods:
public void setName(String n)
public String getName()
This is what I got:
public interface Nameable{
public void setName(String n){
n =name; }
public String getName() {
return n; } }
is this correct or is there a better way of doing this??
4 Answers 4
An interface doesn't specify implementation, so no, this isn't correct.
You must separate the definition of the available methods (the interface) and the implementation (the class) :
public interface Nameable{
public void setName(String n);
public String getName();
}
public class Named implements Nameable {
private String name;
public void setName(String n){
this.name = n;
}
public String getName() {
return this.name;
}
}
Comments
No, you don't define a method in your interface, you only declare them. A class which implements that interface later on, provides the implementation of the method.
is this correct or is there a better way of doing this??
Better way? Yes. Copy this code and paste in your favorite IDE. It will tell you where you are wrong, with so many Red-Marks.
IDE like Eclipse suddenly starts screaming if you create such an interface, and you can tell it to correct it for you. Then you can see the magic.
Comments
You must remember that interfaces only provide method declarations, and do not provide implementation. That is up to the implemented class.
public interface Nameable
{
public void setName(String n);
public String getName();
}
public class NameableImplmentation implments Nameable
{
public void setName(String n)
{
//insert code
}
public String getName()
{
//insert code
}
}
Comments
Your code will gives you Abstract methods do not specify a body.
all the methods of interface are by default abstract, and abstract method has no body, see here abstract
An interface is a group of related methods with empty bodies, but in your code all the methods having the body so that will not compile, see how interface work
more on wiki