How do you call a class in Java?
To call a class in Java, you need to create an object. The specific steps are as follows:
- Import the package where the class is located: Before using it, you need to import the package where the class is located, which can be done using the import statement, for example: import com.example.MyClass;
- Creating objects: use the “new” keyword and constructor method to instantiate a class object, for example: MyClass myObject = new MyClass();
- Invoking methods and accessing properties of a class: To invoke methods and access properties of a class, use the object name followed by the dot operator, such as myObject.methodName(); or myObject.propertyName;
Here is the full example code:
import com.example.MyClass;
public class Main {
public static void main(String[] args) {
// 创建对象
MyClass myObject = new MyClass();
// 调用类的方法
myObject.methodName();
// 访问类的属性
myObject.propertyName = 10;
}
}