gpt4 book ai didi

java - 调用方法的不同方式?

转载 作者:行者123 更新时间:2023-12-02 07:25:10 25 4
gpt4 key购买 nike

我被告知这是调用方法的一种方式:

如果您只写方法或属性的名称,Java 将根据以下规则猜测您在名称之前要写的内容

  1. 如果方法不是静态的,它将尝试查找具有该名称的非静态方法/属性,然后查找静态方法/属性
  2. 如果方法是静态的,它将尝试仅查找静态方法/属性

谁能给我举个例子吗?我无法理解它的含义,因为在找到方法之前它如何知道该方法是否是静态的,但它是根据它是非静态还是静态来找到该方法的?或者他们指的是两种不同的方法或其他什么?

最佳答案

下面是一个示例,其中包含对方法 c、d 和 e 中会发生的情况的适当注释:

class A {
// methods to be looked up
// a static method
static void a() {};
// non-static method
void b() {};


static void c() {
// valid reference to another static method
a();
}

static void d() {
// This would fail to compile as d is a static method
// but b is a non-static
b();
}

// non-static method would compile fine
void e() {
a(); // non-static method can find a static method
b(); // non-static method can find another non-static method
}

}

关于java - 调用方法的不同方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13662887/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com