karlakmkj

Using 'this' on methods

Aug 6th, 2021 (edited)
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.99 KB | None | 0 0
  1. class Computer{
  2.   public int brightness;
  3.   public int volume;
  4.  
  5.   public void setBrightness(int inputBrightness){
  6.     this.brightness = inputBrightness;
  7.   }
  8.  
  9.   public void setVolume(int inputVolume){
  10.     this.volume = inputVolume;
  11.   }
  12.  
  13.   // 'This' method calls other methods from the class. Rather than create a new object, we use this as the object.
  14.   // 'this' serves as a placeholder for whatever object was used to call the original method.
  15.   public void resetSettings(){  
  16.     this.setBrightness(0);
  17.     this.setVolume(0);
  18.   }
  19.  
  20.  
  21.     public static void main(String[] args){
  22.         Computer myComputer = new Computer();
  23.         myComputer.setBrightness(8);
  24.         myComputer.setVolume(24);
  25.         System.out.println(myComputer.brightness);
  26.         System.out.println(myComputer.volume);
  27.         myComputer.resetSettings();  //now both attributes will be reset to 0
  28.         System.out.println(myComputer.brightness);
  29.         System.out.println(myComputer.volume);
  30.     }
  31. }
Add Comment
Please, Sign In to add comment