欢迎访问宙启技术站
智能推送

Java函数使用案例:如何实现函数的重载和重写?

发布时间:2023-07-04 14:58:24

函数重载和函数重写是Java中两个重要的概念。

函数重载是指在同一个类中,存在多个同名函数,但参数列表不同的情况。函数重载可以根据调用时传入的参数的不同,自动选择对应的函数进行调用。函数重载的目的是为了提高代码的复用性和灵活性。下面是一个函数重载的例子:

public class OverloadExample {
    public void print(String str){
        System.out.println(str);
    }
    
    public void print(int num){
        System.out.println(num);
    }
    
    public void print(String str, int num){
        System.out.println(str + num);
    }
    
    public static void main(String[] args){
        OverloadExample example = new OverloadExample();
        example.print("Hello");                // 调用print(String str)方法
        example.print(10);                     // 调用print(int num)方法
        example.print("Java", 8);              // 调用print(String str, int num)方法
    }
}

上述例子中,同名的print方法被定义了三次,分别接受不同类型的参数。在main函数中,根据传入的参数类型不同,自动选择对应的函数进行调用。

函数重写是指子类重新定义了父类中已经存在的同名方法的情况。函数重写是实现Java中的多态性的一种方式。子类重写父类的方法后,当通过父类的引用调用该方法时,会调用子类中重写的方法,而不是父类中的方法。下面是一个函数重写的例子:

public class OverrideExample {
    public void print(){
        System.out.println("This is the parent class");
    }
}

public class ChildClass extends OverrideExample{
    @Override
    public void print(){
        System.out.println("This is the child class");
    }
    
    public static void main(String[] args){
        OverrideExample example = new ChildClass();
        example.print();               // 调用子类中重写的print方法
    }
}

上述例子中,ChildClass继承自OverrideExample,并重写了父类中的print方法。在main函数中,通过父类的引用example调用print方法,实际上调用的是子类中重写的方法。输出结果为"This is the child class"。

函数重载和函数重写都是Java中灵活使用函数的方式,可以根据不同的需求实现不同的功能。函数重载通过参数列表的不同来实现,而函数重写通过子类覆盖父类中的同名方法来实现。