Java 中的设置方法

发布于 2024-10-30 05:21:23 字数 360 浏览 3 评论 0原文

有人可以解释一下如何使用 set 方法吗?问题:

class Sonum {
   private int prior;
   public Sonum(int prior) {
      this.prior = prior;
   }
   public int getPrior() {
      return prior;
   }
   public void setPrior(int prior) {
      this.prior = prior;
   }

class Tel {
   // Please explain how can I set the value for prior? (for example 2)
}

Could anubody explain how to use set methods? Problem:

class Sonum {
   private int prior;
   public Sonum(int prior) {
      this.prior = prior;
   }
   public int getPrior() {
      return prior;
   }
   public void setPrior(int prior) {
      this.prior = prior;
   }

class Tel {
   // Please explain how can I set the value for prior? (for example 2)
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

吾性傲以野 2024-11-06 05:21:24

好吧,首先您需要一个要在其上设置 prior 值的 Sonum 实例。例如:

class Test {
  public void foo() {
    Sonum sonum = new Sonum(5);
    // Use it with a prior of 5
    // ...
    sonum.setPrior(10);
    // Now use it with a prior of 10
  }
}

Well, first you need an instance of Sonum on which you want to set the prior value. For example:

class Test {
  public void foo() {
    Sonum sonum = new Sonum(5);
    // Use it with a prior of 5
    // ...
    sonum.setPrior(10);
    // Now use it with a prior of 10
  }
}
单调的奢华 2024-11-06 05:21:24
Sonum mySonum = new Sonum(1); //prior is currently 1
mySonum.setPrior(2); //now prior is 2
Sonum mySonum = new Sonum(1); //prior is currently 1
mySonum.setPrior(2); //now prior is 2
少跟Wǒ拽 2024-11-06 05:21:24

深吸一口气。 Java 教程。阅读它。你会明白的。

Take a deep breath. The Java Tutorial. Read it. You will understand.

权谋诡计 2024-11-06 05:21:24

“Setter 方法”并不是魔法。它们只是常规方法。您需要该类的一个实例,然后可以调用它的方法。就像任何其他 Java 对象一样。

"Setter methods" aren't magic. They're just regular methods. You need an instance of that class, and then you can call the methods on it. Just like any other Java object.

季末如歌 2024-11-06 05:21:24

set方法处理一个私有值,我们希望阻止他直接使用我们的客户端方式,因此有get\set方法。

get\set方法最大的优点就是控制能力!
例如,当我们想要设置年龄时,我们可以控制最低年龄,以及许多其他简单的示例。

示例:

setAge (int age)
{
    if ( age < 0 )
    {
        System.out.println ( "Wrong age !!" );
    }
}

现在我想您可以轻松理解这个硬件了:)

set method deal with a private value that we would like to prevent the direct way to him using our client, therefor there are get \ set method.

The biggest advantage of get \ set methods is the control ability !
We can for example control a minimum age when we want to set an age, and many other simple examples.

Example:

setAge (int age)
{
    if ( age < 0 )
    {
        System.out.println ( "Wrong age !!" );
    }
}

Now I think you can easily understand this HW :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文