java类中如何调用方法调用方法
在Java类中调用方法
在Java中,调用方法需要遵循特定的语法规则,具体取决于方法的类型(静态方法或实例方法)以及方法的访问权限。以下是几种常见的方法调用方式:
调用实例方法
实例方法属于类的对象,必须通过类的实例来调用。
public class MyClass {
public void instanceMethod() {
System.out.println("This is an instance method.");
}
public static void main(String[] args) {
MyClass obj = new MyClass(); // 创建类的实例
obj.instanceMethod(); // 通过实例调用方法
}
}
调用静态方法
静态方法属于类本身,可以直接通过类名调用,无需创建实例。

public class MyClass {
public static void staticMethod() {
System.out.println("This is a static method.");
}
public static void main(String[] args) {
MyClass.staticMethod(); // 通过类名直接调用
}
}
调用其他类中的方法
如果需要调用其他类中的方法,需要确保方法的访问权限允许(如public),并通过类名或实例调用。
public class AnotherClass {
public void anotherMethod() {
System.out.println("Method from AnotherClass.");
}
}
public class MyClass {
public static void main(String[] args) {
AnotherClass anotherObj = new AnotherClass();
anotherObj.anotherMethod(); // 调用其他类的方法
}
}
方法链式调用
如果方法返回一个对象,可以连续调用方法,形成链式调用。

public class ChainExample {
public ChainExample method1() {
System.out.println("Method1");
return this;
}
public ChainExample method2() {
System.out.println("Method2");
return this;
}
public static void main(String[] args) {
new ChainExample().method1().method2(); // 链式调用
}
}
调用父类方法
在继承关系中,子类可以通过super关键字调用父类的方法。
public class Parent {
public void parentMethod() {
System.out.println("Parent method.");
}
}
public class Child extends Parent {
public void childMethod() {
super.parentMethod(); // 调用父类方法
}
}
递归调用方法
方法可以调用自身,形成递归。
public class RecursionExample {
public void recursiveMethod(int n) {
if (n > 0) {
System.out.println(n);
recursiveMethod(n - 1); // 递归调用
}
}
public static void main(String[] args) {
new RecursionExample().recursiveMethod(5);
}
}
注意事项
- 确保方法的访问权限允许调用(如
public、protected或默认权限)。 - 静态方法不能直接调用实例方法,除非通过实例。
- 实例方法可以调用静态方法。
- 递归调用时需注意终止条件,避免无限递归。






