从其他类调用非静态方法 [英] Calling non-static methods from other classes

查看:46
本文介绍了从其他类调用非静态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做作业,遇到了一些错误.在一个类中,我有此方法:

I'm doing my assignment, and have run into some errors. In one class I have this method:

public class Class1{
    public static boolean winningRecord(){
        final int WINNING_RECORD;
        return Class2.getPoints() > WINNING_RECORD;
    }
}

class Class2{
    int wins = 0;
    public int getPoints(){
        return wins; //More to it but to keep it simple I'll leave that out
    }
}

现在,我收到错误消息无法从静态上下文中引用非静态方法...",因此我将getPoints()设置为静态方法,并将变量也设置为静态,并且它可以正常工作.但是在另一种打印对象的方法中,它不起作用(我相信是因为使用了static关键字).

Now I'm getting the error "Non-Static method cannot be referenced from a static context...", so I made getPoints() a static method, made the variables static as well, and it works. But in another method for printing out Objects it doesn't work (I believe it's because of the static keyword).

那么我的问题是,有没有一种方法可以调用一个方法而不创建第二个Class的实例呢?这是我的基本构想代码,它应该使您了解发生了什么,否则,我将添加更多内容.

So my question after all this is there a way to call a method without creating an instance of the second Class? This is the general idea code that I have, it should give you an understanding of what is going on, if not I'll add more to it.

推荐答案

java中的一个关键概念是实例化的概念.类定义具有针对一种类型的对象的所有规则.对象的每个实例将遵循相同的规则.例如,如果我定义

A key concept in java is the idea of instantiation. A class definition has all the rules for one type of object. Each instance of the object will follow the same rules. For example, if I define

class Ball {
  public void bounce() { 
    // lots of code here
  }
}

然后,系统具有用于称为 Ball 的东西的代码,这些东西可以反弹

Then the system has code for things called Balls which can bounce

如果我想要两个球...

If I want two balls...

public class Main {
  public static void main(String args[]) {
    Ball beachBall = new Ball();
    Ball soccerBall = new Ball();

然后我就可以弹跳它们

    beachBall.bounce();
    beachBall.bounce();
    soccerBall.bounce();
    beachBall.bounce();

但我不能说

    Ball.bounce();

因为这使我的系统中出现哪个球?"这个问题

because that leaves my system with the question "Which ball?"

static 方法和变量与特定实例无关.

static methods and variables are not associated with specific instances.

例如:

class Werewolf {
  static boolean fullMoon = false;

  static void setFullMoon(boolean isVisible) {
    fullMoon = isVisible;
    // code code code
  }

  void eatPerson(Person p) {
    // code code code
  }
}

适用于所有狼人的静态方法,因此在类上被调用:

The static method applied to all werewolves so it is called on the class:

Werewolf.fullMoon(true);

应用于特定狼人的非静态(实例)方法,因此在实例上被调用.

The non-static (instance) method applied to a particular werewolf so it is called on an instance.

jeff.eatPerson(chuck);

杰夫是狼人.查克就是他吃的人.尝试忽略残酷的评论.我们都从某个地方开始.

Jeff is the werewolf. Chuck is the person he eats. Try to ignore the cruel comments. We all started somewhere.

这篇关于从其他类调用非静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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