How is a class defined in Java?
In Java, to define a class, you need to use the keyword class followed by the name of the class, and the content of the class should be enclosed in a pair of curly braces. Below is an example of defining a simple class:
public class MyClass {
// 成员变量
private int myField;
// 构造方法
public MyClass(int myField) {
this.myField = myField;
}
// 方法
public void myMethod() {
System.out.println("This is my method.");
}
}
The example above defines a class named MyClass, which consists of a private integer member variable called myField, a parameterized constructor MyClass, and a method myMethod that does not return a value.