Anon
Anon

Reputation: 109

Trouble calling constructor with input parameters from main

I am trying to play around with Java, and create a small poker game using object oriented principles. However, I'm running into a problem calling a constructor from main.

class Card
{
    private char face;
    private char suit;

    Card(char face, char suit)
    {
      this.face = face;
      this.suit = suit;
    }

    @Override
    public String toString()
    {
      return Character.toString(face) + Character.toString(suit);
    }
}

public static void main(String[] args)
{
    Card oneCardHand = new Card('A', 'c');

    System.out.println("Made it this far");
    System.out.println(oneCardHand);
}

I get the following error:

non-static variable this cannot be referenced from a static context

So I feel like I'm either missing a silly syntax thing, or more likely, not understanding a key insight about static and non-static variables.

Upvotes: 1

Views: 39

Answers (2)

Raymond Loman
Raymond Loman

Reputation: 1

You could make separate classes in .java files

  • public class Application in Application.java with the main method in there
  • public class Card in Card.java

You could also make separate packages but that's probably for later...

Upvotes: 0

Eng.Fouad
Eng.Fouad

Reputation: 117597

The Card class is declared as instance inner class. Either:

  • Convert it to a static inner class:
static class Card
  • Or, create an instance of the outer class to get instance of the inner class (assuming the outer class is called Outer):
Outer.Card oneCardHand = new Outer().new Card('A', 'c');
  • Or, move the main method inside the Card class.

  • Or, move the Card class to separate source file (Card.java), which is commonly the preferable approach.


Read more about nested classes:

Upvotes: 1

Related Questions