zoukankan      html  css  js  c++  java
  • Nested Class

    1. Why Use Nested Classes?

    There are several compelling reasons for using nested classes, among them:

    • It is a way of logically grouping classes that are only used in one place.
    • It increases encapsulation.
    • Nested classes can lead to more readable and maintainable code.

    2. Taxonomy of Classes

    2.1 Static Nested Classes

    A static nested class is associated with its outer class. And like static class methods, a static nested class cannot refer directly to instance variables or methods defined in its enclosing class — it can use them only through an object reference.

    2.1.1 Create an object for the static nested class

    OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();
    2.1.2 When to use static nested class
    B is A's assistant class and only be used by A, define B as A's static nested class like JDK's LinkedList and it's Entry.
     

    2.2 Inner Classes

    As with instance methods and variables, an inner class is associated with an instance of its enclosing class and has direct access to that object's methods and fields. Also, because an inner class is associated with an instance, it cannot define any static members itself.

    2.2.1 Instantiate an inner class

    OuterClass.InnerClass innerObject = outerObject.new InnerClass();
    2.2.2 Obtain outer class's reference
    OuterClass.this
    2.2.3 When to use
    Inner class's most important feature is it can access outer class's any fields or methods, for example, in JDK's Collection
    library, every collection must provide a according Iterator to support unified collection traversal.
     
    2.3 Anonymous Inner Classes
     An inner class within the body of a method without naming it

    2.3.1 When to use

    The class has few code to implement

    Taxonomy of Classes in Java Programming

    版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 相关阅读:
    bzoj4165 矩阵 堆维护多路归并
    bzoj2802 [Poi2012]Warehouse Store 贪心+堆
    bzoj1367 [Baltic2004]sequence 左偏树+贪心
    bzoj3011 [Usaco2012 Dec]Running Away From the Barn 左偏树
    uoj207 共价大爷游长沙 子树信息 LCT + 随机化 + 路径覆盖
    bzoj4764 弹飞大爷 LCT
    bzoj4817 & loj2001 [Sdoi2017]树点涂色 LCT + 线段树
    bzoj5020 & loj2289 [THUWC 2017]在美妙的数学王国中畅游 LCT + 泰勒展开
    bzoj4998 星球联盟 LCT + 并查集
    bzoj3091 城市旅行 LCT + 区间合并
  • 原文地址:https://www.cnblogs.com/significantfrank/p/4875855.html
Copyright © 2011-2022 走看看