Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the meaning of that "we change behavior of any object at runtime in java"

Tags:

java

runtime

I am reading , Orielly Design patterns and there is a line that "We can change the Behavior of any object at runtime" & how getters and setters are used to changed the Behavior of object at runtime .

like image 763
Tushar Avatar asked Apr 02 '13 08:04

Tushar


1 Answers

The behavior is how the object works. Run time is the application life. So that statement means that during the run of program we are able to manipulate what object can do.

To simulate that please see following example:

public class MyObjectTest {

  public static final void main(String[] args) {

   MyObject myObject = new MyObject(); 

   String theMessage = "No message yet.";

   theMessage = myObject.readSecretMessage();

   myObject.setIsSafe(true);

   theMessage = myObject.readSecretMessage();

  }
}


public class MyObject {

 private boolean isSafe = false;


 public boolean isSafe() {
    return this.isSafe;
 } 

 public boolean setIsSafe(boolean isSafe) {
   return this.isSafe = isSafe;
 }

 public String readSecretMessage() {

   if(isSafe()) {
    return "We are safe, so we can share the secret";
   }
   return "They is no secret message here.";
 }
}

Analysis:

The program will return two different messages, the decision depend on the field isSafe. That can be modified during object life (object life start with operator new) in run time.

And that what it means, that we can change the behavior of object.

like image 170
Damian Leszczyński - Vash Avatar answered Oct 10 '22 09:10

Damian Leszczyński - Vash