0

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??

Jigar Joshi
241k42 gold badges409 silver badges446 bronze badges
asked Oct 11, 2012 at 17:32

4 Answers 4

6

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;
 }
}
answered Oct 11, 2012 at 17:32
Sign up to request clarification or add additional context in comments.

Comments

2

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.

answered Oct 11, 2012 at 17:33

Comments

0

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
 } 
}
answered Oct 11, 2012 at 17:37

Comments

0

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

answered Oct 12, 2012 at 5:04

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.