htrap1
htrap1

Reputation: 21

non static method cannot be referenced from a static context problem in Java

This is the instructions on what to do : Display the names and balances of all three accounts. Using if statements, print the name and balance of the Bank Account object that has the largest amount of money (based on the values you chose). You may need to add additional methods to your Bank class (Get Methods).

This is my code:

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;
    }
    }

I am getting this error: non-static method larmo() cannot be referenced from a static context

Why, and what can I do to fix this.

Upvotes: 1

Views: 19131

Answers (2)

Jasneet Dua
Jasneet Dua

Reputation: 4262

We cannot access non static member from a static member directly.

If you want to access that larmo method():

  • Either you should make the larmo method as static
  • or, create an instance of Bank class and use that instance to call the larmo method

Upvotes: 0

Andi
Andi

Reputation: 162

In your case you should change the method to be public static void larmo()

static because the method does not need access to the Bank instance. This also allows it to be called from static context.

void because you do not return any value from the method.

Upvotes: 1

Related Questions