0

Consider this is interface:

public interface Node {
    Node next();
    Node prev();
    void setNext(Node next);
    void setPrev(Node prev);
    void setVal(int val);
    int getVal();
}

I want know how I can instantiate this class, for example:

Node p = tail;

I would like to use it something like this.

1
  • Create a class that implements the interface, and then instantiate the new class: Node p = new SomeClassThatImplementsNode(); Commented Oct 14, 2013 at 13:22

4 Answers 4

2

you cant create instance for an interface , Instead make some class to implement this interface and create instance for that class

public class NodeImpl implements Node{
// your impl     
 }

then

 NodeImpl tail = new NodeImpl();
 Node p =tail;
Sign up to request clarification or add additional context in comments.

1 Comment

You can just do: Node tail = new NodeImpl();
2

Node is an interface, not an interface class (there is no such thing). In a nutshell, you cannot instantiate an interface or an abstract class; you can only instantiate a concrete class.

To take your example, if tail is of type that's either Node or is a class/interface that implements/extends Node, then the assignment will just work.

If you need to create a new object, the code would look something like:

public interface Node { ... }

public class NodeImpl implements Node { ... }

Node p = new NodeImpl();

Comments

0

For the interface you can only do something like that for the initialization (anonymous class):

Node p = new Node() {
    public Node next() {}
    public Node prev() {}
    public void setNext(Node next) {}
    public void setPrev(Node prev) {}
    public void setVal(int val) {}
    public int getVal() {}
};

and implement all the methods. Otherwise you can create an example class:

class NodeImpl implements Node {
    public Node next() {}
    public Node prev() {}
    public void setNext(Node next) {}
    public void setPrev(Node prev) {}
    public void setVal(int val) {}
    public int getVal() {}
}
Node p = new NodeImpl();

Comments

0

It's better to create a class implementing this interface.

But, you still could write:

Node n = new Node() {
  //and here you MUST implement all Node methods
};

Comments

Your Answer

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.