简体   繁体   中英

java access public class method without creating object

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

Since in the method showAll():

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

the only field ( ie, 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 (ie, public static void AddDrink(Drink d ) .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM