Skip to content
Related Articles

Related Articles

Improve Article

Law of Demeter in Java – Principle of Least Knowledge

  • Last Updated : 22 Feb, 2021

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:

  1. Method M of an object O can invoke the method of O itself
  2. Method M can call methods of any parameter P
  3. Method M can call objects created within M
  4. Method M in object O can invoke methods of any type of object that is a direct component of O

Implementation: 



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.

Example 

Java




// Java Program to illustrate Law of Demeter or
// Least knowlledge principle
// where 
// Method M of an object O can invoke
// the method of O itself
  
// Importing input output classes
import java.io.*;
  
// Class 1
// Helper class
class Helper {
  
    // Method of this class
    void M()
    {
  
        // Print statement whenever method is called
        System.out.println("hello from M()");
  
        // 'this' keyword is valid as method named-
        // anotherMethod() is encapsulated in the same class
        this.anotherMethod();
    }
  
    // Method of this class
    void anotherMethod()
    {
  
        // Print statement whenever method is called
        System.out.println(
            "I am anotherMethod() of same class");
    }
}
  
// Class 2
// Main class
class GFG {
  
    // Main driver method
    public static void main(String[] args)
    {
  
        // Creating an object of above Helper class and
        // in the main() method
        Helper obj = new Helper();
  
        // Method M of an object O can invoke
        // the method of O itself
        obj.M();
    }
}
Output
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.

Example 



Java




// Java Program to illustrate Law of Demeter or
// Least knowlledge principle
// where 
// Method M can call methods of any parameter P
  
// Importing all input output classes
import java.io.*;
  
// Class 1
// Helper class  
class Human{
  
    // Method of Human class 
    public void speak() {
  
        // Print message whenever function is called
        System.out.println("Hello Dog");
    }
}
  
// Class 2
// Helper class 
class Dog{
  
    // Method of Dog class
    public void M(Human P) {
  
        // We can call methods of object 
        // passed in our parameter
        P.speak();
  
        // Print message whenever function is called
        System.out.println("Bark(_-_)");
    }
}
  
// Class 3
// Main class
class Main {
  
    // Main driver method 
    public static void main (String[] args) {
          
        // Creating object of Human Class and Dog class
        // inside the main method
        Human h = new Human();
        Dog obj = new Dog();
  
        // Method M calling any parameter P
      // M-> method of Dog class
      // h-> Human class object 
        obj.M(h);
    }
}
Output
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.

Example 

Java




// Java Program to illustrate Law of Demeter or
// Least knowlledge principle
// where 
// Method M can call objects created within M 
  
// Importing all input output classes
import java.io.*;
  
// Class 1
// Helper class  
class Human {
  
    // Method of thos class
    public void speak() {
  
        // Print statement whenever the method is called
        System.out.println("Hello Dog");
    }
}
  
// Class 2
// helper class 
class Dog {
  
    // Method of Dog class
    public void M() {
  
        // We can use object P as it is local
        // to this method and satisfy 3rd law
        Human P = new Human();
        P.speak();
  
        // Print statement whenever the method is called
        System.out.println("Barks-_-");
    }
}
  
// Class 3
// Main class
class GFG {
    public static void main (String[] args) {
          
        // Creating an object of Dog class
        // in the main() method
        Dog obj = new Dog();
  
        // Method M can call objects created
        // within M 
        obj.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.

Example 

Java




// Java Program to illustrate Law of Demeter or
// Least knowlledge principle
// where 
// Method M in object O can invoke methods 
// of any type of object that is a direct component of O
  
// Importing all input output classes
import java.io.*;
  
// Class 1
// Helper class  
class Human {
    
    // Method of Human class
    public void speak() {
        
        // Print statement whenever the function is called
        System.out.println("Hello Dog!");
    }
}
  
// Class 2
// helper class
class Dog {
      
    // Instance Variable
    Human P; 
    
    // Method of Dog class
    public void M() {
        
        // We can use P as it is an Instance Variable
        // of class dog
        P = new Human();
          
        // Calling speak() method over instance variable  
        P.speak();
          
        // Method of Dog class
        System.out.println("Barks!");
    }
}
  
// Main class
class Main {
    
    // Main driver method 
    public static void main (String[] args) {
        
        // Creating object of Dog class
        // in the main() method  
        Dog obj = new Dog();
          
        obj.M();
    }
}
Output
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.




My Personal Notes arrow_drop_up
Recommended Articles
Page :