Java syntax to invoke a constructor of a static nested class

659 Views Asked by At

I learnt that static class is a class whose members MUST be accessed without an instance of a class.

In the below code from java.util.HashMap, jdk 1.8,

public class HashMap<K,V> extends AbstractMap<K,V>
    implements Map<K,V>, Cloneable, Serializable {

        .........

        static class Node<K,V> implements Map.Entry<K,V> {
             final int hash;
             final K key;
             V value;
             Node<K,V> next;

             Node(int hash, K key, V value, Node<K,V> next) {
                this.hash = hash;
                this.key = key;
                this.value = value;
                this.next = next;
             }
             ........
         }
         ..........
}

What is the java syntax to invoke a constructor

Node(int hash, K key, V value, Node<K,V> next){...}

of a nested static class Node?

3

There are 3 best solutions below

2
scottb On

I learnt that static class is a class whose members MUST be accessed without an instance of a class.

More correctly, a static nested class is a class whose instances are instantiated without any reference to an instance of the enclosing class.

A static nested class is regarded as a member of the enclosing class (along with its methods and fields). However, in every way that matters, a static nested class functions just like a top level class.

To create an instance of a static nested class, you use this syntax:

EnclosingClass.MemberClass myInstance = new EnclosingClass.MemberClass();
2
Bob Kuhar On

I don't think you can "see" that static inner class; it is package protected and you generally don't see people trying to jack their stuff into any of the java.* packages.

This compiles, but yuk. I didn't even know you could hijack the java.* packages in this manner.

package java.util

import java.util.HashMap;
import java.util.Map;

public class InstantiateNode {

  public static void main(String[] args) {
    HashMap.Node<String,String> mapNode = new HashMap.Node<String, String>(1, "hey", "you", null);
  }
}
0
Anonymous Coward On

None, there is no sintax for that.

Node has package access. This means you cannot access from code outside of the package where HashMap belongs to.

In the unlikely case that you are writing code inside that package the sintax would be :

HashMap.Node<KeyType, ValueType> node = 
   new HashMap.Node<>(hash, key, value, nextNode );