简体   繁体   English

Java调用方法非/静态和私有/公共

[英]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? a)如果我在SalesMethod类中,并且想从region方法中调用sales方法,我该怎么做? ( private method calling public method) private方法调用public方法)

b) What about sales calling purchase? b)销售电话叫什么呢? ( public calling public from within same class) (来自同一班级的public呼吁public

c)If I was in SalesMethod , what would be a way to call the futureSales method? c)如果我在SalesMethod ,将如何调用futureSales方法? 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
  }
}

a) private method calling public method is ok since public mean "visible from everywhere". a)私有方法调用public方法是可以的,因为public的意思是“随处可见”。

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

b) public method calling public method is ok for the same reason. b)出于相同的原因,调用public方法是可以的。

b') public method calling private method is ok if the private method is in the same class than the public one. b')如果私有方法与公共类在同一类中,则调用私有方法的公共方法是可以的。

c) to call a non-static method, you have to create an instance since you call it "on" an object. c)调用非静态方法,您必须创建一个实例,因为您将其“对象”调用了。 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. 静态是指“相对于类”,非静态是相对于对象的,您可以将其视为对象执行的动作。

If I was in the SalesMethod class and I wanted to call the sales method from the region method how would I do that? 如果我在SalesMethod类中,并且想从region方法中调用sales方法,我该怎么做? (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? 如果我在SalesMethod中,那么调用futureSales方法的方法是什么? Would I have to create an instance for it since it's non static? 由于它是非静态的,是否需要为其创建实例?

Yes. 是。

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

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

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