Memory Map
This is section is about Interface vs Class and in-depth content on usage of each.
Following rules are described:
- Item 15: Minimize the accessibility of classes and members
- Item 16: In public classes, use accessor methods, not public fields
- Item 17: Minimize mutability
- Item 18: Favor composition over inheritance
- Item 19: Design and document for inheritance or else prohibit it
- Item 20: Prefer interfaces to abstract classes
- Item 21: Design interfaces for posterity
- Item 22: Use interfaces only to define types
- Item 23: Prefer class hierarchies to tagged classes
- Item 24: Flavor static member classes over non-static
- 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-
- Ambiguity in case of lack of Documentation – The case of counting elements of Hashset<>:
- there are 2 mehods adding elments to hashset like: add() and addAll()
- the case is- that we have to count number of elements in hash set .
- we add 3 elements using addall(),and then when we call to user defined function count it RETURNS 6.
- 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.
- [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.
- Ambiguity in case of lack of Documentation – The case of counting elements of Hashset<>:
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