简体   繁体   English

“我们在Java运行时更改任何对象的行为”的含义是什么?

[英]what is the meaning of that “we change behavior of any object at runtime in java”

我正在阅读Orielly Design模式,并且有一行“ We can change the Behavior of any object at runtime ”以及如何使用getter和setter在运行时更改对象的行为。

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 . 程序将返回两个不同的消息,取决于字段isSafe的决定。 That can be modified during object life (object life start with operator new ) in run time. 这可以在运行时的对象生命期间(使用operator new启动对象生命期间)进行修改。

And that what it means, that we can change the behavior of object. 这意味着我们可以改变对象的行为。

Let me walk the cats on 2 and 4 legs alternately at the runtime :).. basically, this means that you can change the behavior of Cat at runtime using getters and setters. 让我在运行时交替在2条腿和4条腿上行走猫:) ..基本上,这意味着您可以在运行时使用getter和setter更改Cat的行为。

class Cat
{
    int legs = 2;

    public void walk() {
       System.out.println("Walking on " + legs + " legs");
    }

    public int getLegs()
    {
       return legs;
    }

    public void setLegs(int legs)
    {
       this.legs = legs;
    }
}

public void static main()
{
     Cat c = new Cat();
     c.setLegs(4);
     c.walk();

     c.setLegs(2);
     c.walk();
}

On the face of it, it is meaningless, or at least incorrect. 从表面上看,它是没有意义的,或者至少是不正确的。 You can change an object's properties, but not its behaviour (except of course to the extent that its behaviour depends on the values of its properties). 您可以更改对象的属性,但不能更改其行为(当然,除非它的行为取决于其属性值)。 You would have to supply more context to make sense of this. 您必须提供更多上下文才能理解这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM