1

so I'm fairly new to Java and I've looked up a lot of information on static methods and static fields, and nothing seems to really answer my question so I'm going to ask it here. I'm creating a program that uses an arrayList of Card objects and performs methods on those card objects. For example:

Card chooseNewCard() {
    currentCardIndex = num;
    return myCards.get(currentCardIndex);
}

With the myCards being the name of the array.List I'm not sure if 2 part questions are allowed but my question(s) is should a method like this be static, and if so what does that say about where the objects of the class should be created? To clarify the last part, when you're dealing with static objects, should the objects be created near the instance variables, or in the main method or within another method?

Thank you in advance, again I'm very new to Java so I could be thinking about this the entire wrong way.

Alex T.
  • 13
  • 3
  • If you declare the method static than all the fields defined inside it need to be static too – Arun Jun 06 '20 at 21:57
  • Specific cases matter; here, I think you're just looking for `myCards[index]`. – chrylis -cautiouslyoptimistic- Jun 06 '20 at 22:09
  • 1). Yes, but... surely `myCards` shouldn't be static, a `Deck` `class` would probably be a sensible wrapper. 2). I'm assuming you're talking specifically about creating the elements of some `static` container like an array? It depends really, if you're always expecting the array to be populated with an exact amount of elements then `static` initialization is the way to go. – George Jun 06 '20 at 22:13
  • If you have an array of cards, presumably they are part of a deck. If you have a static array, then you can only have ONE deck of cards. If you need to have multiple decks of cards then the array should NOT be static. – Idle_Mind Jun 06 '20 at 22:13
  • `With the myCards being the name of the array` - In this case, your code won't compile. You can not call `get` method on an array. – Arvind Kumar Avinash Jun 06 '20 at 22:37
  • @George, yes the arrayList is always going to have the same number of elements in it, so I have a follow up question. If the elements in the arrayList are object from class Cards, is there a way to make the objects static when I declare them, or should the instance variables be static? – Alex T. Jun 07 '20 at 01:58

3 Answers3

2

There isn't enough information here to be sure of answering your question. I don't have a definition for num, and there is no get() method on an array, you just put the index into brackets: myCards[currentCardIndex].

A static method would reasonably be used to perform an operation related to all the objects in a program (as opposed to being related to one object). I'm not sure what you mean by "static objects", and the proper location of the creation of objects depends entirely on their use in the program you're writing. So I think you're going to need to go back to what you want to know and rephrase the question. I know it's difficult in a subject you're unsure about in the first place, but there's only so much we can guess and assume about what you're doing.

arcy
  • 12,845
  • 12
  • 58
  • 103
  • Num is just a variable storing a random number and it's an array list not an array, sorry. – Alex T. Jun 07 '20 at 01:47
  • You're going to have to use basic terms correctly in order to get help on a programming. I still don't understand what it is you want to know. – arcy Jun 07 '20 at 02:20
2

Whether the argument is an array or some other object is irrelevant. Typically, use a static method when there is no Object state (i.e. instance fields) involved in determining the answer. Check out the java.lang.Math class for examples of this.

Since you cannot access an instance field from a static method you have no choice but to use instance methods when performing computations involving instance fields.

Static methods can also be used to create factory methods. In this case the normal constructor is private an you have static methods that return specialized instances of the class. An example of that is the javax.swing.BorderFactory class.

WJS
  • 36,363
  • 4
  • 24
  • 39
0

So static variables will update across all instances of the specified class. On the other hand, static methods allow you to access a function within a class without creating a instance, therefore you cannot access any non-static fields because they would only exist if the a new instance is created. Take a look at the following example at a simple class I created below to explain the concept:

  public class Employee
{
    private static int idcount = 1;
    private int id;

    public Employee()
    {
        this.id = idcount;
        idcount++; //cant use "this" with static variables
    }

    public int getId()
    {
        return this.id;
    }

    public static int getIdCount()
    {
        return idcount; //can only use static variables
    }

    public static void main (String [] args)
    {
        Employee employee1 = new Employee();
        Employee employee2 = new Employee();

        System.out.println(employee1.getId()); //will print 1
        System.out.println(employee2.getId()); // will print 2
        System.out.println(Employee.getIdCount()); // will print 3 and see how the static method is called straight on the Employee class and not a instance
    }

}

So if you run the java class above you will see that static variable will get updated across both instances of the Employee class.

So for your problem what you could do is have a card class and within you have a static variable that holds the Card instances that are created and a static method that gets a specific card for example

import java.util.ArrayList;

public class Card
{
    private static ArrayList<Card> Cards = new ArrayList<Card>();
    private int index; //field to store the index of the card in the array
    private String name; //test field

    public Card(String name)
    {
        this.name = name;
        this.index = Cards.size();
        //when you create a new card add it to the list
        Cards.add(this);

    }

    public int getIndex()
    {
        return this.index;
    }

    public String getName()
    {
        return this.name;
    }

    public static Card getCard(int index)
    {
        return Cards.get(index);
    }

    public static void main(String [] args)
    {
        Card KingOfClubs = new Card("King Of Clubs");
        Card KingOfHearts = new Card("King Of Hearts");

        System.out.println(Card.getCard(KingOfClubs.getIndex()).getName()); // will print King of Clubs
        System.out.println(Card.getCard(KingOfHearts.getIndex()).getName()); // will print King of Hearts


    }
}

I have no clue on what your actually doing so i just wanted to explain to you how static variables and method works. Hope this helped you.