Java 中的调用方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28888518/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 14:20:40  来源:igfitidea点击:

Calling methods in Java

javamethodscall

提问by m.cekiera

I'm a beginner and I'm trying to get a grasp on methods in Java. In general, I understand differences between static and non-static methods, but sometimes, reading others code, I'm confused about how a particular call is written.

我是初学者,我正在尝试掌握 Java 中的方法。一般来说,我理解静态和非静态方法之间的区别,但有时,在阅读其他代码时,我对如何编写特定调用感到困惑。

As I understand, static method can be called with or without object. Non-static method need an object to be called, however when non-static method is called in another non-static method, in written form, it can be called just by a name(like method()), without a written reference to object (like object.method()or this.method()).

据我了解,可以使用或不使用对象调用静态方法。非静态方法需要一个对象被调用,但是当非静态方法在另一个非静态方法中被调用时,以书面形式,它可以只通过一个名字(如method())来调用,而不需要一个书面的引用对象(如object.method()this.method())。

Is there another situation, when a non-static method call can be written this way? Is there another way to call a method beyond those?

还有另一种情况,当非静态方法调用可以这样编写时?除了这些之外,还有其他方法可以调用方法吗?

I would be grateful for any comments.

如有任何意见,我将不胜感激。

回答by spudone

Maybe you're thinking of a call to a method within the same class, e.g.:

也许您正在考虑调用同一类中的方法,例如:

public class Foo {
    public void doSomething() {
        doSomethingElse();   // equivalent to "this.doSomethingElse()"
    }

    private void doSomethingElse() {
        System.out.println("Bar");
    }
}

回答by tsumnia

Let's not worry about static/non-static for a second, that's another can of worms. Let's think about what kind of programs you've mostly built so far; perhaps you've designed a program like calculating the distance between two (x,y) coordinates.

让我们暂时不要担心静态/非静态,那是另一种蠕虫。让我们想想到目前为止您主要构建了哪些类型的程序;也许您已经设计了一个程序,例如计算两个 (x,y) 坐标之间的距离。

public static void main(String[] args) {
    double x1 = 4.0;
    double y1 = 3.0;
    double x2 = 4.0;
    double y2 = 4.0;

    double x = Math.pow(x2 - x1, 2);
    double y = Math.pow(y2 - y1, 2);
    double distance = Math.sqrt(x+y);
    System.out.println("The distance is" + distance);
}

Now, what happens if you want to use that code in a more complex program, like a video game to determine if your character is colliding into a wall? Now you have 3 coordinates(A and B are the Wall and C is the Character) and you'll need to find out the distance between all three coordinates (AB, AC, and BC). Why? Because if AB == AC + BC, then our character has ran into a wall! Here's a video explaining why this will work by yours truly: Collision Detection of 2D Points

现在,如果您想在更复杂的程序(如视频游戏)中使用该代码来确定您的角色是否撞墙,会发生什么?现在您有 3 个坐标(A 和 B 是墙,C 是角色),您需要找出所有三个坐标(AB、AC 和 BC)之间的距离。为什么?因为如果AB == AC + BC,那么我们的角色就撞墙了!这是一段视频,解释了为什么这对您真正有用:2D 点的碰撞检测

Do I want to have to repeatedly type the same formula? Or waste time copying and pasting? No, I'm lazy. That's why I program the computer to do things for me.

我是否需要重复输入相同的公式?还是浪费时间复制粘贴?不,我很懒。这就是为什么我编写计算机程序来为我做事的原因。

What I CANdo, however, is design tiny, little programs that can run inside my big, main program. These are called methods.

CAN做的,但是,是设计出能我的大,主程序运行里面的小,小程序。这些被称为方法

public static double distance(double x1, double y1, double x2, double y2) {
    double x = Math.pow(x2 - x1, 2);
    double y = Math.pow(y2 - y1, 2);
    double dist = Math.sqrt(x+y);
    return dist;
}

Now, notice that I did two things differently.

现在,请注意我做了两件不同的事情。

One, I named my variable dist instead of distance; it's just good programming practice not to name your variables the same as your method.

一,我将变量命名为 dist 而不是 distance;不要将变量命名为与方法相同的名称,这只是一种良好的编程习惯。

Two, I threw in a return statement. Now, think about the first program I showed, what's it doing when it's done? Nothing. It prints to the screen and that's it. It shuts down and clears out memory. But what if I need the distance later? Well, that's where returncomes in. It makes sure that after doing the calculations, before clearing out of memory, it wants to give it back to you.

二,我抛出了一个return 语句。现在,想想我展示的第一个程序,当它完成时它在做什么?没有什么。它打印到屏幕上,就是这样。它关闭并清除内存。但是如果我以后需要距离怎么办?嗯,这就是return 的用武之地。它确保在完成计算之后,在清除内存之前,它想把它还给你。

If you've learned about Math.random(), notice that you need to store or use it, otherwise it's gone for good. That's because Math.random()has a return typeof a double. Something like System.out.println()has a return type of voidbecause it doesn't 'return' anything, just displays text to our screen.

如果您已经了解了Math.random(),请注意您需要存储或使用它,否则它就一去不复返了。这是因为Math.random()有一个返回类型一的。类似的东西System.out.println()有一个void返回类型,因为它不“返回”任何东西,只是在我们的屏幕上显示文本。

The basic premise behind a method is:

方法背后的基本前提是:

<access modifier> <return type> <name> (<parameters>) { }

<access modifier> <return type> <name> (<parameters>) { }

The access modifier, for right now, should just stay public static. You'll learn about classes later. The return typeis the important thing because this like like when you make a variable; you had to tell Java what data type it was - same for a method. You have to tell Java what data type this tiny, little program will produce. nameis no different than when you named variablesbut now, you have to add in parameters, which are just placeholders in the method because we don't know what the values/variables that will be used later are going to be!

现在,访问修饰符应该保持不变public static。稍后您将了解类。这return type是很重要的事情,因为这就像你创建一个变量一样;你必须告诉 Java 它是什么数据类型 - 对于方法也是如此。你必须告诉 Java 这个小小的程序会产生什么数据类型。name与命名变量时没有什么不同,但是现在,您必须添加 in parameters,它们只是方法中的占位符,因为我们不知道稍后将使用的值/变量是什么!

Now that I have distanceas a method, I can use it three times whereever I want:

现在我有了distance一个方法,我可以在任何我想要的地方使用它三遍:

double distAB = distance(4, 0, 4, 4);
double distAC = distance(4, 0, 4, 2);
double distBC = distance(4, 4, 4, 2);
if (distAB == distAC + distCB)
    System.out.println("Collision Detected");

回答by Laerte

Basically, you can call non-static methods like this: method();or this.method();

基本上,您可以像这样调用非静态方法:method();this.method();

When you use the second syntax with this, you will be telling the compiler that you will be calling from the instance you are in (explicit).

当您使用第二个语法 with 时this,您将告诉编译器您将从您所在的实例调用(显式)。

Both will work the same way.

两者的工作方式相同。

But, there is another example that can set this clear for you. Thinking on variables. Check this code:

但是,还有另一个示例可以为您清楚地说明这一点。对变量的思考。检查此代码:

private int a = 1;

public void method(int a) {
    this.a = a;
}

The object's variable is set using a local variable. If you do not use thisfor that call, the compiler would understand that the variable you are dealing with was just the local one.

对象的变量是使用局部变量设置的。如果您不使用this该调用,编译器会理解您正在处理的变量只是本地变量。

Hope it helps.

希望能帮助到你。

回答by a_mid

When you write thisin a class in Java (or when it is implied), you are refering to the object instanciating that class so thisis a reference to an object not a class. This is hard to get at first but there is a difference between the concept of object and class in object oriented programming and therefore in Java.

当您this在 Java 中编写类时(或当它被暗示时),您this是在引用实例化该类的对象,因此是对对象的引用而不是类。一开始很难理解,但是在面向对象编程中对象和类的概念之间存在差异,因此在 Java 中也是如此。

Note also that when you call a static method, you use the name of the class containing the static method because the static method is a concept defined for the class not the particular objects instanciating that class.

另请注意,当您调用静态方法时,您使用包含静态方法的类的名称,因为静态方法是为类定义的概念,而不是实例化该类的特定对象。