【问题标题】:non static method cannot be referenced from a static context problem in Java不能从 Java 中的静态上下文问题中引用非静态方法
【发布时间】:2021-03-21 06:33:53
【问题描述】:

这是有关操作的说明: 显示所有三个帐户的名称和余额。使用 if 语句,打印名称和 拥有最大金额的银行账户对象的余额(基于您的值 选择)。您可能需要向您的 Bank 类添加其他方法(获取方法)。

这是我的代码:

import java.util.*;
public class Bank
{
    public Bank()
    {
        double checkingBal = 0.0;
        double savingsBal = 0.0;
    }
    public static void main(String[] args)
    {
        System.out.println("Problem 1");
        Bank tom = new Bank();
        Bank rohan = new Bank();
        Bank parth = new Bank();
        tom.setChecking(10000);
        parth.setChecking(60000);
        rohan.setChecking(700000);
        larmo();  
    }
    public void setChecking(double val)
    {
        double checkingBal = val;
    }
    public Bank larmo()
    {
        System.out.println(tom.getChecking());
        System.out.println(rohan.getChecking());
        System.out.println(parth.getChecking());
        if (tom.getChecking()>parth.getChecking() && tom.getChecking()>rohan.getChecking())
        {
            System.out.println("Name: Tom, Balance: "+tom.getChecking());
        }
        if (parth.getChecking()>tom.getChecking() && parth.getChecking()>rohan.getChecking())
        {
            System.out.println("Name: Parth, Balance: "+parth.getChecking());
        }
        if (rohan.getChecking()>tom.getChecking() && rohan.getChecking()>parth.getChecking())
        {
            System.out.println("Name: Rohan, Balance: "+rohan.getChecking());
        }
        System.out.println("Congratulations to the richest man in the bank");
    }
    public double getChecking()
    {
        return checkingBal;
    }
    }

我收到此错误: 不能从静态上下文中引用非静态方法 larmo()

为什么,我可以做些什么来解决这个问题。

【问题讨论】:

  • 根据上面的代码,这个错误只是你需要修复的第一个错误。您真的应该尝试理解变量范围、实例状态和类成员的概念。

标签: java non-static


【解决方案1】:

在您的情况下,您应该将方法更改为public static void larmo()

static 因为该方法不需要访问 Bank 实例。这也允许从静态上下文中调用它。

void 因为您没有 return 方法中的任何值。

【讨论】:

    【解决方案2】:

    我们不能直接从静态成员访问非静态成员

    如果你想访问那个larmo method()

    • 您应该将 larmo 方法设为静态
    • 或者,创建 Bank 类的实例并使用该实例调用 larmo 方法

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-01
      • 1970-01-01
      • 2019-05-21
      相关资源
      最近更新 更多