我们常常在编写好一个函数后会在其他类中使用
跨类使用函数可以通过以下几种方式实现:
1. 继承:通过继承关系,子类可以继承父类的函数,并且可以直接调用。子类可以重写父类的函数,实现自己的逻辑。这样就可以在子类中使用父类的函数。
2. 接口:接口是一种约定,定义了一组函数的规范。一个类可以实现或多个接口,并且需要实接口中定义的所有函数。通过实接口,可以在不同的类中使用相同的函数。
3. 组合:组合是指一个类中包含其他类的对象作为成员变量。通过在类中创建其他类的对象,可以使用其他类中定义的函数。
4. 委托:委托是一种将函数作为参数传递给其他函数或对象的机制。通过委托,可以在一个类中调用另一个类中的函数。
public class Index{
public static void main(String[] args){
System.out.println("helloworld!");
}
public static void hello(){
System.out.print("in hello!");
}
}
public static void main(String[] args){
System.out.print("test hello!");
hello2();//调用
}
public static void hello1(){
System.out.print("in hello!");
}