简体   繁体   English

Java:如何从类中创建的对象调用类方法?

[英]Java: How to call a class method from an object created in the class?

I have a class let's say School in which I create an object Student.我有一个班级,比如说 School,我在其中创建了一个对象 Student。 How would I call from Student class a method that is located in the School class without making it static?如何从 Student 类调用位于 School 类中的方法而不使其成为静态方法?

Here's a quick example:这是一个快速示例:

public class School(){
 Student s1 = new Student();

 public void createNewStudent(){
 Student s2 = new Student();
 }

}


public class Student(){

School.createNewStudent();

}

Thank you in advance!先感谢您!

Create an instance of School class within your Student class在 Student 类中创建 School 类的实例

ex:前任:

School school = new School();
school.createNewStudent();

In java, class method are static method.在java中,类方法是静态方法。

public class MyClass{
  public static void myClassMethod() {
    System.out.println("inside class method");
  }

  public void myInstanceMethod() {
    MyClass.myClassMethod();
  }

  public static void main (String args[]) {
    MyClass.myClassMethod();
    MyClass myInstance = new MyClass();
    myInstance.myInstanceMethod();
  }
}

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

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