java怎样进行非静态引用_关于java:从方法内部对非静态方法进行静态引用

我理解"无法对非静态方法进行静态引用"错误,但我遇到了这个:

public class MyClass {

public static void main(String[] args) {

MyClass myClassInstance = new MyClass();

while (true) {

myClassInstance.myMethod();

myMethod();//Cannot make a static reference to the non-static method myMethod()

}

}// END main

void myMethod() {

try {

//Stuff

}

} catch (Exception e) {

myMethod();

}

}// END myMethod

}// END MyCLass

我不能只从main调用myMethod()但我可以从方法本身内部执行此操作(在这种情况下,如果发生异常,我想再次调用myMethod())。

这是如何运作的? 是myClassInstance仍然不知何故,因为那时我还在myMethod()里面?

在类级别拥有static MyClass myClassInstance = new MyClass()然后每次调用myClassInstance.myMethod()会更好吗?

当然你不能。 另一种方法是MyClass类的实例的一部分,而不是类本身。 你真的应该学习类和对象方法

myMethod是一个实例方法。 调用使用myMethod()相当于this.myMethod()。 在myMethod()中,这是一个实例方法,this存在:它是当前对象。 在main()里面,这是一个静态方法,没有this。 所以这个电话没有意义。

首先,您应该了解有关静态和非静态方法的更多信息:

A static method belongs to the class

and a non-static method belongs to an

object of a class. That is, a

non-static method can only be called

on an object of a class that it

belongs to. A static method can

however be called both on the class as

well as an object of the class. A

static method can access only static

members. A non-static method can

access both static and non-static

members because at the time when the

static method is called, the class

might not be instantiated (if it is

called on the class itself). In the

other case, a non-static method can

only be called when the class has

already been instantiated. A static

method is shared by all instances of

the class. These are some of the basic

differences. I would also like to

point out an often ignored difference

in this context. Whenever a method is

called in C++/Java/C#, an implicit

argument (the 'this' reference) is

passed along with/without the other

parameters. In case of a static method

call, the 'this' reference is not

passed as static methods belong to a

class and hence do not have the 'this'

reference.

参考:静态Vs非静态方法

How does this work? is myClassInstance still somehow there because at

that point I'm still inside myMethod()?

myMethod是属于myClassInstance的实例方法。 所以当你在myMethod()里面调用myMethod()时,它相当于this.myMethod()

Would it be better to have static MyClass myClassInstance = new MyClass() at class level and then call myClassInstance.myMethod() every time?

当我们将类的成员声明为static时,意味着无论创建了多少个类的对象,都只有一个静态成员的副本。 静态成员由类的所有对象共享。 如果没有其他初始化,则在创建第一个对象时,所有静态数据都将初始化为零。 有关更多信息,请访问静态变量:好还是坏?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值