Reputation: 109
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
Reputation: 1
You could make separate classes in .java files
You could also make separate packages but that's probably for later...
Upvotes: 0
Reputation: 117597
The Card
class is declared as instance inner class. Either:
static class Card
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