简体   繁体   English

如何从未在Java中实例化的类中调用方法?

[英]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 在您的main方法中,创建Friend类的实例

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? 您知道static字段和方法吗? 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 然后,在您的main方法中,您可以简单地将其调用为

Friend.sayHello();

This is an example of calling a method on a class that is not instantiated in Java. 这是在未用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. 在此示例中,我创建了Friends,并将其存储在数组中。

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 用Java创建对象的不同方法

  1. Using new keyword 使用新关键字

This is the most common way to create an object in Java. 这是用Java创建对象的最常用方法。

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

Friend class has a public default constructor so you can create an object in this way. Friend类具有公共的默认构造函数,因此您可以通过这种方式创建对象。

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

The clone() can be used to create a copy of an existing object. clone()可用于创建现有对象的副本。

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. 您可以使用它们中的任何一个来创建对象,然后调用该方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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