java access public class method without creating object

Viewed 101

I'm a beginner in java and I have a Drink class where I have a method showAll() to print all my drink objects that are stored in a private hashset . In my main function I can have access to this method by saying

Drink test = new Drink(value1 , value2 , ....);
test.showAll();

Is there a way to access my showAll() method without creating an object as I just want to print all the array objects without the need to create a new object each time I want to print

Drink.java

private static HashSet<Drink> drinks = new HashSet(); //store all drinks in hashset 

  public void AddDrink(Drink d ){ //add a drink 
     try {
          drinks.add(d);
     }catch(Exception e ){
         System.out.println(e);
     }
  }
  
  public void showAll() {  //show all drinks 
      for(Drink d : drinks) {
          System.out.println(d);
      }
  }
1 Answers

Since in the method showAll():

  public void showAll() {  //show all drinks 
      for(Drink d : drinks) {
          System.out.println(d);
      }

the only field (i.e., drinks) data that you are using is also static:

private static HashSet<Drink> drinks = new HashSet(); //store all drinks in hashset 

you can turn your method into static:

public void static showAll(){...}

Then you can call that method as Drink.showAll(). Btw you can shorten your showAll method from:

  public void showAll() {  //show all drinks 
      for(Drink d : drinks) {
          System.out.println(d);
      }
  }

to just:

   public static void showAll() {
        drinks.forEach(System.out::println);
    }

by combining forEach with method reference.

In your current design, public void AddDrink(Drink d ) can also be turn into static method as well (i.e., public static void AddDrink(Drink d ).

That all being said, a better design for your class has been proposed on the comments by @JustAnotherDeveloper

Related