static vs non-static member class

roon-replica·2022년 3월 31일
0

java

목록 보기
1/6

stackexchange 글 - static vs non-static 사용 예시

1. static

  • enum이 대표적
    • enum type is implicitly static
  • as a public helper class
  • 장점
    • outer attribute 접근 불가 (Non-static field cannot be referenced from a static context)
      ==> less coupling?
public class Calculator {
    public enum Operation {
        PLUS, MINUS;
    }

    int outerAttr;

    public static void main(String[] args) {
        System.out.println(Operation.PLUS);
    }
}

2. non static

// in java.util.HashMap
final class KeySet extends AbstractSet<K> {
        public final int size()                 { return size; }
        public final void clear()               { HashMap.this.clear(); }
        public final Iterator<K> iterator()     { return new KeyIterator(); }
        public final boolean contains(Object o) { return containsKey(o); }
        public final boolean remove(Object key) {
            return removeNode(hash(key), key, null, false, true) != null;
        }
        public final Spliterator<K> spliterator() {
            return new KeySpliterator<>(HashMap.this, 0, -1, 0, 0);
        }
        public final void forEach(Consumer<? super K> action) {
            Node<K,V>[] tab;
            if (action == null)
                throw new NullPointerException();
            if (size > 0 && (tab = table) != null) {
                int mc = modCount;
                for (Node<K,V> e : tab) {
                    for (; e != null; e = e.next)
                        action.accept(e.key);
                }
                if (modCount != mc)
                    throw new ConcurrentModificationException();
            }
        }
    }
profile
집중 ➝ 프로세서↑ 시간 투자 ➝ 디스크↑

0개의 댓글