首先,要从一个类中访问另一个类的方法,需要确保这两个类之间存在关联,在 Java 中,这种关联通常通过继承和实现实现。
class Parent {
public void print() {
System.out.println("Parent class method");
}
}
class Child extends Parent {
public void print() {
System.out.println("Child class method");
}
}
在上面的例子中,Child 类继承了 Parent 类,并重写了父类中的 print() 方法。因此,在 Child 类中可以直接访问父类中的 print() 方法。
interface Printable {
void print();
}
class MyClass implements Printable {
public void print() {
System.out.println("MyClass method");
}
}
class AnotherClass {
private Printable printable;
public AnotherClass(Printable printable) {
this.printable = printable;
}
public void print() {
this.printable.print();
}
}
在上面的例子中,MyClass 实现了 Printable 接口,并定义了 print() 方法。在 AnotherClass 中,通过引入 Printable 接口创建了一个变量 printable,并通过构造函数将 MyClass 实例传入。这样,在 AnotherClass 中可以通过 printable 变量调用 MyClass 中的 print() 方法。
总之,在 Java 中,类与类之间的关联关系决定了能否通过关联对象访问另一个类的方法。
领取专属 10元无门槛券
手把手带您无忧上云