user4099400
user4099400

Reputation:

Java calling methods non/static and private/public

I just had some method calling scenarios I was unsure of, and was hoping someone could help clear some up for me.

a) If I was in the SalesMethod class and I wanted to call the sales method from the region method how would I do that? (private method calling public method)

b) What about sales calling purchase? (public calling public from within same class)

c)If I was in SalesMethod, what would be a way to call the futureSales method? Would I have to create an instance for it since it's non static?

Thanks in advance.

public class SalesMethod
{
  public static double sales ()
  {
    code
  }
  private static void region ()
  {
    code
  }
  public static double purchase ()
  {
    code
  }
  public void futureSales ()
  {
    code
  }
}

Upvotes: 0

Views: 106

Answers (2)

user3453226
user3453226

Reputation:

If I was in the SalesMethod class and I wanted to call the sales method from the region method how would I do that? (private method calling public method)

They are both static, so you can call them everytime you need to.

sales();
// Or
SalesMethod.sales();

What about sales calling purchase? (public calling public from within same class)

They are both static, so you can call them everytime you need to.

purchase();
// Or
SalesMethod.purchase();

If I was in SalesMethod, what would be a way to call the futureSales method? Would I have to create an instance for it since it's non static?

Yes.

SalesMethod instance = new SalesMethod();
instance.futureSales();

Upvotes: 0

Léo Martel
Léo Martel

Reputation: 31

a) private method calling public method is ok since public mean "visible from everywhere".

 public static double region()
 {
       sales();
 }

b) public method calling public method is ok for the same reason.

b') public method calling private method is ok if the private method is in the same class than the public one.

c) to call a non-static method, you have to create an instance since you call it "on" an object. You can't call it from a static method the way you do in the example above.

static means "relative to a class" non-static is relative to an object, you can see that as an action performed by the object.

Upvotes: 1

Related Questions