[英]How to call a method of an already created object from another class method?
[英]Java: How to call a class method from an object created in the class?
我有一個班級,比如說 School,我在其中創建了一個對象 Student。 如何從 Student 類調用位於 School 類中的方法而不使其成為靜態方法?
這是一個快速示例:
public class School(){
Student s1 = new Student();
public void createNewStudent(){
Student s2 = new Student();
}
}
public class Student(){
School.createNewStudent();
}
先感謝您!
在 Student 類中創建 School 類的實例
前任:
School school = new School();
school.createNewStudent();
在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.