Bob
Bob

Reputation: 10805

set methods in Java

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)
}

Upvotes: 0

Views: 1404

Answers (6)

Batman
Batman

Reputation: 1324

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 :)

Upvotes: 0

dty
dty

Reputation: 18998

"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.

Upvotes: 0

Hardik Mishra
Hardik Mishra

Reputation: 14877

Refer

Creating Objects & Using Objects

http://download.oracle.com/javase/tutorial/java/javaOO/objectcreation.html

Upvotes: 0

Daniel
Daniel

Reputation: 28084

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

Upvotes: 0

Mike Lentini
Mike Lentini

Reputation: 1358

Sonum mySonum = new Sonum(1); //prior is currently 1
mySonum.setPrior(2); //now prior is 2

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1500903

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
  }
}

Upvotes: 3

Related Questions