Gerardo Zinno Gerardo Zinno - 9 days ago 7
Java Question

Using an inner class to create a private record for the outer class in java / inner methods visibility

I have to implement an interface called

Graph<E>
in Java.

Let's say
MyGraph<E extends Comparable<E>>
is the class I'm writing to implement Graph.

I would like to create an inner class
Node
in order to "encapsulate" the elements of Type
E
.

public class MyGraph<E extends Comparable<E>> implements Graph<E>{


MyGraph methods and instance variables...
.
.
.



class Node {
E elem;
List<E> edges;
...
public Node(E e){
this.elem = e;
edges = null;
}
}
}


The problem is I can't understand if the inner class should be
Node
or
Node<E>
,
public
or
private
and if the instance variables of it should be declared
public
or
private
. And the same for some eventual methods I'm going to insert in
Node
.

Basically the class Node should be like a record type in C (with
typedef
), and the outer class should be able to access all the instance variable of Node without observers, getters, etc.

Answer

You should declare the Node class private static as it doesn't need access to the members of the outer class. If you don't do this every instance will carry a reference to the instantiating instance. You will need to give it a parameter to do this.

If you use E as the parameter name it will shadow the E in the outer class, so consider giving it a different name for clarity. Your outer class will have full access to the members of Node, and no other class will have access if Node is private, so you don't need to worry about the access level of the members—just omit them.