user2720690
user2720690

Reputation: 13

A subclass type as parameter type in superclass constructor java

So I have a node class and I haven't learned Linked List yet, so I can't use that. To construct a node object I want the parameters to be like this:

Node(int numberOfNode, type complex or simpel)

I have two subclasses of node called Simpelnode and complexNode and so a node object can be either one of them. What do I need to do so that the parameter can be of both types?

Upvotes: 1

Views: 637

Answers (4)

JB Nizet
JB Nizet

Reputation: 691655

Node(int numberOfNode, Node node)

Since SimpleNode and ComplexNode are both subclasses of Node, a SimpleNode is a Node, and a ComplexNode is a Node. So using Node as the argument type will allow passing a SimpleNode as well as a ComplexNode.

Upvotes: 1

Abhishek Singh
Abhishek Singh

Reputation: 9729

As far as i understood your question..

Make a Node interface with constructor

Node(int numberOfNode,Object o) or Node(int numberOfNode,Node o)

Make two classes implement it SimpleNode and ComplexNode

as follows SimpleNode(int numberOfNode,SimpleNode o) and ComplexNode(int numberOfNode,ComplexNode o)

Upvotes: 0

No Idea For Name
No Idea For Name

Reputation: 11577

you need to create Simpelnode and complexNode and make them extend from Node.

that way you can do:

Node n = new Simpelnode();

or

Node n = new complexNode();

also you should read on java inheritance and to understand what it means

Upvotes: 0

user2110286
user2110286

Reputation:

Use Inheritance

public interface Node{
    //...
}

public class SimpleNode implements Node{
    //...
}

public class ComplexNode implements Node{
    //...
}

Then, you can add a Constructor like that:

public class SimpleNode implements Node{
    public SimpleNode(int numberOfNode){
        //...
    }
}

Upvotes: 3

Related Questions