Law of Demeter in Java – Principle of Least Knowledge
According to the law of Demeter, classes should know about and interact with a few other classes as possible. It is used to loosen the coupling by limiting class interaction with other classes to provide stability as tighter coupling makes the program difficult to maintain. So when we limit classes to communicate with each other we can enforce the principle of the least knowledge. Local objects are passed in parameter, instantiated within a method, or should be an instance variable. In the law of Demeter a method should not invoke methods of any object that is not local.
We are trying to prevent something like A.getObjectB().getObjectC().display() this sort of statement is a violation of Law of Demeter.
Methods: Rules of Law of Demeter
There are primarily 4 principles of the least knowledge in java as follows:
- Method M of an object O can invoke the method of O itself
- Method M can call methods of any parameter P
- Method M can call objects created within M
- Method M in object O can invoke methods of any type of object that is a direct component of O
Now let us figure out them with implementation to get a better understanding
Method 1: Method M of an object O can invoke the method of O itself.
Method encapsulated within a class can call other methods that are encapsulated in the same class.
hello from M() I am anotherMethod() of same class
Method 2: Method M can call methods of any parameter P
Method M can use methods of object P if it is passed as an argument as object P will be local to the Method M.
Hello Dog Bark(_-_)
Method 3: Method M can call objects created within M
If method M makes an object then it can use that object as the object is considered local to method M.
Method 4: Method M in object O can invoke methods of any type of object that is a direct component of O
Method of a class can call methods of another class which are its instance variable.
Hello Dog! Barks!
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.