在Java中,類和方法的調用涉及到以下幾個方面:
class
開始,后跟類名,然后是類的主體,包含在一對大括號{}
中。實例化類時,需要使用new
關鍵字,后跟類名和括號內的構造函數參數(如果有的話)。// 定義一個名為Person的類
class Person {
String name;
int age;
// 構造函數
Person(String name, int age) {
this.name = name;
this.age = age;
}
}
public class Main {
public static void main(String[] args) {
// 實例化一個Person對象
Person person1 = new Person("Alice", 30);
}
}
public
、private
等開始,后跟返回類型(如果需要的話),然后是方法名,接著是括號內的參數列表(如果有的話),最后是方法體,包含在一對大括號{}
中。要調用類中的方法,你需要使用實例(對象)和對象名,后跟方法名和括號內的參數(如果有的話)。
class Person {
String name;
int age;
// 構造函數
Person(String name, int age) {
this.name = name;
this.age = age;
}
// 定義一個名為greet的方法
void greet() {
System.out.println("Hello, my name is " + name + " and I am " + age + " years old.");
}
}
public class Main {
public static void main(String[] args) {
// 實例化一個Person對象
Person person1 = new Person("Alice", 30);
// 調用greet方法
person1.greet();
}
}
在這個例子中,我們定義了一個名為Person
的類,其中包含一個名為greet
的方法。然后,我們在main
方法中實例化了一個Person
對象,并調用了greet
方法。運行這段代碼將輸出:
Hello, my name is Alice and I am 30 years old.