静态方法:无法在静态上下文中引用非静态
来源:互联网 发布:拼豆制作软件 编辑:程序博客网 时间:2024/06/08 05:23
如上是经典的Fobonacci递归算法:
public class Fibonacci { public static void main(String []args) { int x = f(6); System.out.println(x); } public int f(int x) { if(x==1||x==2) return 1; else return f(x-1)+f(x-2); } }
编译后出错,无法在静态上下文中引用非静态。
原来,在静态的方法中不能直接调用非静态的方法或属性。因为一个类的静态方法在这个Class文件被加载之后,就可以由这个Class类型对象来调用,而非静态的方法需要一个实例对象,有可能还未被创建,所以为了避免在静态方法中调用一个还不存在的实例对象的非静态方法,编译期就会直接阻止这个行为。
解决的方法有两种,第一种是将被调用的方法设置成静态方法;第二种是new本类,然后通过实例来调用。
第一种:
public class Fibonacci { public static void main(String []args) { int x = f(6); System.out.println(x); } public static int f(int x) { if(x==1||x==2) return 1; else return f(x-1)+f(x-2); } }第二种:
public class Fibonacci { public static void main(String []args) { Fibonacci f = new Fibonacci(); int x = f.f(6); System.out.println(x); } public int f(int x) { if(x==1||x==2) return 1; else return f(x-1)+f(x-2); } }
阅读全文
0 0
- 静态方法:无法在静态上下文中引用非静态
- 静态方法:无法在静态上下文中引用非静态
- 无法从静态上下文中引用非静态方法
- 无法从静态上下文中引用非静态方法
- 无法从静态上下文中引用非静态变量,非静态方法
- “无法从静态上下文中引用非静态”
- 无法从静态上下文中引用非静态变量
- 无法从静态上下文中引用非静态 变量 this
- 无法从静态上下文中引用非静态 变量 this
- 由“无法从静态上下文中引用非静态方法”引出的疑问
- “无法从静态上下文中引用非静态方法”这个问题怎么解决
- Java静态方法:无法从静态上下文中引入非静态方法
- JAVA学习【2】错误:无法从静态上下文中引用非静态
- 错误: 无法从静态上下文中引用非静态 变量 this
- java编译时出现无法从静态上下文中引用非静态
- JAVA学习【2】错误:无法从静态上下文中引用非静态(转载)
- 初学java:“错误:无法从静态上下文中引用非静态”(在调用类中的类时出现的错误)
- 静态方法中引用非静态变量
- PAT——1040. 有几个PAT
- 【20171014】python_语言设计(9)交互式图形编程
- Windows7的基础上安装CentOS双系统
- python2.7 MySQLdb库的安装
- poj 2349 Arctic Network
- 静态方法:无法在静态上下文中引用非静态
- python学习:列表
- package.json 详解
- 阿里云CentOS7中安装Docker
- PAT——1033. 旧键盘打字
- hdu 3926 hand in hand 同构图
- lua table to string
- package.json和config.js有什么关联么
- 混合编程接口规范