原因: 用static修饰的方法称为静态方法,修饰变量则为静态变量,又分别叫做类方法或者类变量。 静态方法中不能直接调用非静态方法。因为非静态方法不是独立存在的,它是依附于对象存在——即只有申明了对象,才能通过对象调用。而静态方法则可以直
原因:
用static修饰的方法称为静态方法,修饰变量则为静态变量,又分别叫做类方法或者类变量。
静态方法中不能直接调用非静态方法。因为非静态方法不是独立存在的,它是依附于对象存在——即只有申明了对象,才能通过对象调用。而静态方法则可以直接通过类名调用,而不需要申明对象。因此直接引用非静态方法就会出错。
常见的main方法都是静态的,必须由static修饰,因此在main方法里调用类的其他非静态方法,都是需要先申明对象,才能用。否则就会出现引用非静态方法的错误。
静态方法可以不用创建对象就调用,非静态方法必须有了对象的实例才能调用.因此想在静态方法中引用非静态方法是不可能的,因为它究竟引用的是哪个对象的非静态方法呢?编译器不可能给出答案,因为没有对象啊,所以要报错.
实例:
一、
1 public class Solution { 2 public static void main(String[] arvgs){ 3 System.out.println("请输入股票价格"); 4 int[] profit = {1, 2, 3, 4, 5, 6}; 5 6 maxProfit(profit, 5); // 报错 7 8 } 9 public int maxProfit(int prices[], int day){ 10 int maxprofit = 0; 11 for (int i = 0; i < day - 1; i++){ 12 for (int j = i + 1; j < day; j++) { 13 int profit = prices[j] - prices[i]; 14 if (profit > maxprofit) 15 maxprofit = profit; 16 } 17 } 18 return maxprofit; 19 } 20 } ~
由于main方法其实是一个静态方法,而maxProfit方法并没有实例化,
所以会报错 错误: 无法从静态上下文中引用非静态 变量 this
1 public class Solution { 2 public static void main(String[] arvgs){ 3 System.out.println("请输入股票价格"); 4 int[] profit = {1, 2, 3, 4, 5, 6}; 5 Solution solution = new Solution(); 6 solution.maxProfit(profit, 5); 7 8 } 9 public int maxProfit(int prices[], int day){ 10 int maxprofit = 0; 11 for (int i = 0; i < day - 1; i++){j 12 for (int j = i + 1; j < day; j++) { 13 int profit = prices[j] - prices[i]; 14 if (profit > maxprofit) 15 maxprofit = profit; 16 } 17 } 18 return maxprofit; 19 } 20 } ~
二、
第一种:将需要调用的方法/变量设置成static,就可以直接调用了
第二种:先创建一个实例对象,通过实例对象调用non-static方法就可以变成直接调用的变量/方法
package com.bjsxt.thread.thread_extends;//线程一://乌龟 100 兔子100public class MyThreadNew { public static void main(String[] args) { //兔子 ThreadTest threadTest = new ThreadTest(); threadTest.setName("兔子"); threadTest.start(); //乌龟 ThreadTest threadTest1 = new ThreadTest(); threadTest1.setName("乌龟"); threadTest1.start(); } class ThreadTest extends Thread { @Override public void run() { // Thread.currentThread().getName():获取当前线程的名字 for (int i = 1; i <= 100; i++) { System.out.println(Thread.currentThread().getName() + "跑了" + i + "米"); } } }}
package com.bjsxt.thread.thread_extends;//线程一://乌龟 100 兔子100public class MyThreadNew { public static void main(String[] args) { //兔子 ThreadTest threadTest = new ThreadTest(); threadTest.setName("兔子"); threadTest.start(); //乌龟 ThreadTest threadTest1 = new ThreadTest(); threadTest1.setName("乌龟"); threadTest1.start(); }} class ThreadTest extends Thread { @Override public void run() { // Thread.currentThread().getName():获取当前线程的名字 for (int i = 1; i <= 100; i++) { System.out.println(Thread.currentThread().getName() + "跑了" + i + "米"); } } }
来源地址:https://blog.csdn.net/m0_54250366/article/details/128822574
--结束END--
本文标题: 无法从静态上下文中引用非静态方法
本文链接: https://www.lsjlt.com/news/394087.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-04-03
2024-04-03
2024-04-01
2024-01-21
2024-01-21
2024-01-21
2024-01-21
2023-12-23
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0