创建类的全局实例 - JAVA [英] Make global instance of class - JAVA

查看:232
本文介绍了创建类的全局实例 - JAVA的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这段代码中,我试图创建类的全局实例,以便任何方法都可以使用它:

  public static void clip(){
while(!Display.isCloseRequested()){
glClear(GL_COLOR_BUFFER_BIT);

if(character.gravity)character.y ++; //有错误,它说变量字符不存在
Display.update();
Display.sync(70);



public static void initGame(){
entity character = new entity(); //我想在方法clip()中使用它
character.create(true,box,true);
}

我搜索了google,但在我的问题中 什么都没发现。
感谢您的帮助。

解决方案

java中没有像全局变量那样的东西。



然而,你可以通过声明来声明字符作为类变量。 b
$ b

  entity character = new entity(); 

以外的方法,仅限于类作用域。



类似的东西:

  class MyClass {
private static entity character = new entity(); //类变量! (!!Display.isCloseRequested()){
glClear(GL_COLOR_BUFFER_BIT);
public static void clip(){
;

if(character.gravity)character.y ++;
Display.update();
Display.sync(70);



public static void initGame(){
character = new entity(); //它会'重置'游戏并将一个新对象绑定到类变量'character'。
character.create(true,box,true);


code
$ b

有关类变量的更多信息可以在官方文档中。



作为一个边节点,一个类不应该被命名为 entity ,因为java有一个强大的约定,即类名应该总是以大写字母开头,您应该将此类重命名为实体


In this code, I am trying to make global instance of class so any methods can use it:

public static void clip(){
    while(!Display.isCloseRequested()){
        glClear(GL_COLOR_BUFFER_BIT);

        if(character.gravity)character.y++; //there is an error, it says "Variable character does not exist"            
        Display.update();
        Display.sync(70);
    }
}

public static void initGame(){
    entity character = new entity(); // I want to use this in method clip()
    character.create(true, "box", true);
}

I've searched google, but on my question "Make instances of class global" found nothing. Thanks for help.

解决方案

There is no such thing as a "global variable" in java.

However, you can declare character as a class variable by declaring:

entity character = new entity();

outside of methods, only on the class scope.

Something like that:

class MyClass { 
  private static entity character = new entity(); //class variable!
  public static void clip(){
      while(!Display.isCloseRequested()){
          glClear(GL_COLOR_BUFFER_BIT);

          if(character.gravity)character.y++; 
          Display.update();
          Display.sync(70);
      }
  }

  public static void initGame(){
      character = new entity(); // it will 'reset' game and bind a new object to the class variable `character`.
      character.create(true, "box", true);
  }
}

More info on class variables can be in the official documentation.


As a side node, a class should not be named entity, since java has a strong convention that classes names should always start with upper case letter, you should rename this class to Entity.

这篇关于创建类的全局实例 - JAVA的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆