java中非静态变量的调用_在调用静态方法非静态方法在Java中(非静态变量错误) (Calling non-static method in static method in Java (Non-S...

在Java中调用非静态方法需要类的实例。你可以选择创建类的实例或者将要调用的方法改为静态。创建子类并不会使方法变为静态,也无法在没有实例的情况下调用非静态方法。选项A是创建实例,适用于需要多次调用方法的情况。选项B是将方法设为静态,适合于方法不依赖任何对象且只访问静态变量和调用静态方法的情况。
摘要由CSDN通过智能技术生成

If you want to call a non-static method (i.e., an instance method) you need an instance of the class. It's as simple as that. So you have two possibilities: a) either make sure you have an instance of the class (this is your option 1), or b) make the method you want to call static. Which one is best in your case depends on your specific code, which you haven't provided.

Creating a subclass does not make a method static and it does not make a non-static method callable without an instance. Anyway, in your code snippet you are not creating any subclass.

A: Create an instance

You can call an instance method only if you have an instance of the class. It may be that it is cumbersome to create an instance because the constructors are very elaborate, but it may be that your instance methods needs this information in order to correctly function.

However, often you do not need to create a new instance every time you need to call the method; you can create a new instance once and use that every time:

class Foo {

Bar instance;

Foo() {

instance = new Bar(/* lots of parameters */);

}

void f() {

// ...

instance.sA2s(input1);

// ...

instance.sA2s(input2);

// ...

}

}

B: Make method static

It can be that your method sA2a doesn't depend on any object, for example because it only accesses static variables (and local variables) and only calls static methods. In that case you can make it static. Static methods can be called from a static context.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值