简体   繁体   English

如何声明这样的函数?

[英]How do I declare a function like this?

How can I declare a function like damagePlayer below in Java? 如何在下面的Java中声明类似damagePlayer的函数?

player.getPlayer1().damagePlayer(50);

I already know that we have to declare something like this to get it: 我已经知道我们必须声明这样的内容:

ServerPlayer player = new ServerPlayer();

But, how do we put the second function ( GetPlayer() ) in the first place? 但是,如何将第二个函数( GetPlayer() )放在首位呢? I'm learning Java, and this would be an awesome way to save code. 我正在学习Java,这将是一种很棒的保存代码的方法。

Declare methods on class named Player , that will work. 在名为Player类上声明方法 ,该方法将起作用。

public Player getPlayer(){
    return this;
}

public void damagePlayer(int damage){
    ...
}    

It's just one way. 这只是一种方式。

Answer is - first method must return object which is an instance of the Player class, where method damagePlayer is. 答案是-第一个方法必须返回对象,该对象是Player类的实例,方法damagePlayer在其中。

player.getPlayer1().damagePlayer(50);

damagePlayer(50) would be written as a method of the type that getPlayer1() returns. DamagePlayer(50)将被编写为getPlayer1()返回的类型的方法。 So implement your damagePlayer(int x) class in the class whose instance player.getPlayer1() returns. 因此,在其实例player.getPlayer1()返回的类中实现您的DamagePlayer(int x)类。

so if getPlayer1() returns an object of the type (or class ) Foo , you would write the damagePlayer method in the Foo class. 因此,如果getPlayer1()返回Foo类型(或class)的对象,则可以在Foo类中编写DamagePlayer方法。

eg. 例如。

Bar bar = new Bar();
bar.doThis().doThat(25) ;

class Bar{
  public Foo doThis() {
    Foo foo=new Foo();
    //do some thing using foo

    return foo;
  }
}

class Foo() {

  void doThat(int number){
    // can do anything using parameter number and return anything
  }

}

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

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