java如何调用其他类
调用其他类的基本方法
在Java中,调用其他类主要通过实例化对象或直接调用静态成员实现。以下是常见场景的示例:
实例化对象调用
通过创建目标类的对象,访问其非静态成员(方法或属性):
// 定义目标类
public class TargetClass {
public void printMessage() {
System.out.println("Hello from TargetClass");
}
}
// 调用类
public class Main {
public static void main(String[] args) {
TargetClass obj = new TargetClass(); // 实例化
obj.printMessage(); // 调用方法
}
}
调用静态成员
若目标类的方法或属性为static,可直接通过类名访问:

public class UtilityClass {
public static void showInfo() {
System.out.println("Static method called");
}
}
public class Main {
public static void main(String[] args) {
UtilityClass.showInfo(); // 无需实例化
}
}
跨包调用类的注意事项
若目标类位于不同包,需确保:
- 目标类为
public修饰。 - 使用
import语句导入目标类,或使用全限定名(包名+类名)。// 在com.example.utils包中 package com.example.utils; public class StringHelper { public static String format(String text) { return text.toUpperCase(); } }
// 在另一个包中调用
import com.example.utils.StringHelper;

public class Main {
public static void main(String[] args) {
String result = StringHelper.format("test");
System.out.println(result);
}
}
### 通过继承调用父类方法
子类可通过`super`关键字调用父类的非私有方法或属性:
```java
public class ParentClass {
protected void display() {
System.out.println("Parent method");
}
}
public class ChildClass extends ParentClass {
@Override
public void display() {
super.display(); // 调用父类方法
System.out.println("Child method");
}
}
接口与实现类调用
通过接口类型引用实现类对象,实现多态调用:
public interface Service {
void execute();
}
public class ServiceImpl implements Service {
@Override
public void execute() {
System.out.println("Service implementation");
}
}
public class Main {
public static void main(String[] args) {
Service service = new ServiceImpl();
service.execute();
}
}
反射调用类(高级用法)
通过反射机制动态调用类的方法,适用于运行时才确定类名的情况:
import java.lang.reflect.Method;
public class ReflectionExample {
public static void main(String[] args) throws Exception {
Class<?> clazz = Class.forName("com.example.TargetClass");
Object obj = clazz.getDeclaredConstructor().newInstance();
Method method = clazz.getMethod("printMessage");
method.invoke(obj);
}
}
以上方法覆盖了Java中调用其他类的常见场景,根据具体需求选择合适的方式。






