简体   繁体   中英

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?

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){
        //...
    }
}
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 .

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM