Calling external methods without instantiating an object

I was wondering if it is possible to call methods of an external class without actually declaring an object of this class. They, as I configure it, calls the ArrayList stored in the object, is emptied every time a method is called that uses the object.

If I can call a method without an object, then I can fix my problem.

Thanks in advance.

calling class:

 public class BookingScreen extends Activity {

    GAClass sendApplication = new GAClass();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_booking_screen);
    }

    public void saveBookingInfo(View view) {

        EditText applicantNameText = (EditText) findViewById(R.id.applicantNameTextField);
        EditText itemToBurnText = (EditText) findViewById(R.id.itemToBurnTextField);

        String appName = applicantNameText.getText().toString();
        String appItemToBurn = itemToBurnText.getText().toString();

        if (appItemToBurn.isEmpty() || appName.isEmpty()) {
            Toast.makeText(BookingScreen.this, "Please fill in all fields.", Toast.LENGTH_SHORT).show();
        }
        else {
            sendApplication.storeApplication(appName, appItemToBurn);
            this.finish();
        }
   }

The outer class of the method:

     public class GAClass {

    ArrayList<Application> peopleAttending;


    public void storeApplication(String name, String item){
        peopleAttending = new ArrayList<>(10);
        peopleAttending.add(new Application(name, item));

   }
  }
+4
source share
3 answers

Use static methods. You can call a static method without creating an object of the surrounding class.

https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html

+3
source

-

public class GAClass {

    public static ArrayList<Application> peopleAttending=null;


    public static void storeApplication(String name, String item){
        if(null==peopleAttending){
          peopleAttending = new ArrayList();
        }
        peopleAttending.add(new Application(name, item));

   }
  }

,

 GAClass.storeApplication(str_name,str_item);

peopleAttending arraylist static,

if(null==peopleAttending){
              peopleAttending = new ArrayList();
            }

, peopleAttending 9s null

+4

What exactly are you trying to achieve? The methods staticin the class would not need an instance of the class, so you can make the methods you need (which do not require the state of the object, i.e. Do not need a specific object to work with) staticand name them as follows:

ClassWithStaticMethods.staticMethod() ;

0
source

Source: https://habr.com/ru/post/1584217/


All Articles