简体   繁体   中英

How do I call a method from a class that was not instantiated in Java?

I would like to start off by apologizing for the bad title. I know the title can be improved, but I do not know the term that is appropriate. Help with the title is appreciated.

As for my question, I am curious if I can call a method from the 'Friend' class. I'm not sure how to explain my question, so I hope this code helps.

public class Main {
  public static void main(String args[]) {

  int friends = 0;

  while(friends < 3) {
    new Friend().talk("Hello");
    friends ++;

    try {
      Thread.sleep(500);
    } catch(InterruptedException e) {
      e.printStackTrace();
    }

  }

  // How do I call the 'goodbye()' method from one of the 'Friend' classes?

  }
}

Friend Class:

public class Friend {

  int talk = 0;

  public Friend() {
  }

  public void talk(final String word) {

    Thread speech = new Thread() {
      public void run() {

        while(talk < 5) {
          System.out.println(talk + ": " + word);

          try {
              Thread.sleep(1000);
           } catch (InterruptedException ie) {
               ie.printStackTrace();
           }

          talk ++;
        }

      }
    };

    speech.start();

  }

    public void goodbye() {
      talk = 5;
    }

}

Please let me know if I can call the methods from classes if I create the class objects like I showed above. Also, if someone could please tell me the proper term for calling methods from classes like I showed, it would be a huge help. Thanks in advance!

In your main method create an instance of the Friend class

Friend f=new Friend();

then call its methods

f.talk("Hello");
f.goodbye();
...

Doing so you will be referring to the same object. In your case, this is what you get

public static void main(String args[]) {
    int friends = 0;
    Friend f = new Friend();
    while (friends < 3) {
        f.talk("Hello");
        friends++;
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    f.goodbye();
}

Do you know about static fields and methods? They can be called without instantiation. Define a class like

public class Friend {
    public static void sayHello() {
        System.out.println("Hello");
    }
}

Then, in your main method, you can call it simply as

Friend.sayHello();

This is an example of calling a method on a class that is not instantiated in Java. Further reading - Understanding Class Members

If static isn't what you're looking for which I tend to believe because of your comment and where it exists in the code

How do I call the 'goodbye()' method from one of the 'Friend' classes?

then your question is misleading in the sense that you really are instantiating objects. In this example I create Friends and store them in an array.

public static void main(String args[]) {

    int count = 0;

    //you can store reference to Friend in an array
    Friend[] friends = new Friend[3];

    //in the loop, you make 3 new Friends
    while (count < 3) {
        friends[count] = new Friend();
        count++;
    }

    //Since they're instantiated and stored in the array, you can call their methods later
    friends[0].goodbye();
    //or
    friends[1].goodbye();
    //or
    friends[2].goodbye();
}

Different ways to create objects in Java

  1. Using new keyword

This is the most common way to create an object in Java.

Friend f = new Friend();
f.talk("Hello");
  1. Using Class.forName()

Friend class has a public default constructor so you can create an object in this way.

Friend f = (Friend) Class.forName("Friend").newInstance(); 
  1. Using clone()

The clone() can be used to create a copy of an existing object.

Friend anotherF = new Friend(); 
Friend f= anotherF.clone(); 
  1. Using object deserialization

Object deserialization is nothing but creating an object from its serialized form.

ObjectInputStream inStream = new ObjectInputStream(anInputStream ); 
Friend f= (Friend) inStream.readObject();

You can use any one of them to create object and then call the method.

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