Java里面static不能修饰局部变量

本文探讨了Java中静态方法无法直接调用非静态方法的问题,并提供了两种解决方案:一是将方法声明为静态并使用全局静态变量;二是创建类的实例并通过该实例调用非静态方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

https://blog.youkuaiyun.com/q610376681/article/details/49359819/

java 中 Cannot make a static reference to the non-static 解决方法

今天敲代码的时候遇到了这个问题,大体这个问题可以简化成这样;

public class Test1 {
public String get()
{
return "123";
}
public static void main(String[] args)
{
String string =get();
}
}

1
2
3
4
5
6
7
8
9
10

显示
Cannot make a static reference to the non-static method get() from the type Test1

好吧,我决定改成这样

public class Test1 {
public String get()
{
return "123";
}
public static void main(String[] args)
{
static String string =get();
}
}

1
2
3
4
5
6
7
8
9
10

可是还是错的。。。。

翻了一下java书才知道

1.java中 静态方法不可以直接调用非静态方法和成员,也不能使用this关键字(这就是这个问题的原因,我用静态的main方法调用了非静态的的get方法)。

原因解释:类中静态的方法或者属性,本质上来讲并不是该类的成员,在java虚拟机装在类的时候,这些静态的东西已经有了对象,它只是在这个类中”寄居”,不需要通过类的构造器(构造函数)类实现实例化;而非静态的属性或者方法,在类的装载是并没有存在,需在执行了该类的构造函数后才可依赖该类的实例对象存在。所以在静态方法中调用非静态方法时,编译器会报错(Cannot make a static reference to the non-static method func() from the type A)。

java中不能将方法体内的局部变量声明为static
main()函数是静态的,没有返回值,形参为数组。
非静态成员的可以随便调用静态成员

原来静态这么反人类,那要this的干什么呢?
大概就是为了使多个类共享一个数据。

大概修改了一下,将函数变为static,将变量声明为全局静态的

方法一:

public class Test1 {
static String string;
public static String get()
{
return "123";
}
public static void main(String[] args)
{
string =get();
System.out.print(string);
}
}

1
2
3
4
5
6
7
8
9
10
11
12

方法二

public class Test1 {
public String get() {
return "123";
}
public static void main(String[] args) {
Test1 c = new Test1();
String string = c.get();
System.out.print(string);
}
}

转载于:https://blog.51cto.com/maplebb/2153891

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值