Classes and Interface

Memory Map

This is section is about Interface vs Class and in-depth content on usage of each.

Following rules are described:
  1. Item 15: Minimize the accessibility of classes and members
  2. Item 16: In public classes, use accessor methods, not public fields
  3. Item 17: Minimize mutability
  4. Item 18: Favor composition over inheritance
  5. Item 19: Design and document for inheritance or else prohibit it
  6. Item 20: Prefer interfaces to abstract classes
  7. Item 21: Design interfaces for posterity
  8. Item 22: Use interfaces only to define types
  9. Item 23: Prefer class hierarchies to tagged classes
  10. Item 24: Flavor static member classes over non-static
  11. Item 25: Limit source files to a single top-level class

Highlights of section

Terms
Implementation inheritance- when a class extends another class and
Interface inheritance– when a class implements interface or an interface extends another interface.

Loopholes in using Inheritance:

  • [WRONG Statement]The problems with overriding methods-
    1. Ambiguity in case of lack of Documentation – The case of counting elements of Hashset<>:
      1. there are 2 mehods adding elments to hashset like: add() and addAll()
      2. the case is- that we have to count number of elements in hash set .
      3. we add 3 elements using addall(),and then when we call to user defined function count it RETURNS 6.
      4. Blunder !!!! so internally addAll calls add() method and so it us inserted twcie . this issue occured beasue[Conclusion] there is no documentation for the fact that addAll() call add internally.
    2. [The case of having predicate before adding in a: ]
      • the problem in inheritance in which method is added not overridden. Suppose you add a method and then in later releases java library also releases method with same signature in super class then your class will be fragile class.
summary :


Use inheritance after aptly analysing if there exists IS-A relationship then class B can extends class A i.e class-B IS-A class-A.
Inherit a class only if it made to be inherited else have proper documentation to avoid blunder as we saw in case 1

Enum Anatomy

Better option for declaring constants as provide more functionality than properties files(constructor, mutators, accessors )

  1. Item 34: Use enums instead of int constants
  2. Item 35: Use instance fields instead of ordinals
  3. Item 36: Use EnumSet instead of bit fields
  4. Item 37: Use EnumMap instead of ordinal indexing
  5. Item 38: Emulate extensible enums with interfaces
  6. Item 39: Prefer annotations to naming patterns
  7. Item 40: Consistently use the Override annotation
  8. Item 41: Use marker interfaces to define types