Android 多态:子类抽象函数返回值类型详解
在 Android 中,多态是指一个对象可以有多种不同的形态。在 Java 中,子类可以通过继承父类并重写父类的方法来实现多态。
子类可以在重写父类的抽象函数时,返回与父类函数定义的返回类型相同或者是其子类类型的变量。这是因为子类可以作为父类的一种形态存在,因此可以返回父类或子类类型的变量。
例如,假设有一个父类 Animal 和它的两个子类 Dog 和 Cat。Animal 类有一个抽象函数 getSound(),返回类型为 String。在子类 Dog 和 Cat 中,可以重写 getSound() 函数并返回不同的字符串。
示例代码如下:
abstract class Animal {
public abstract String getSound();
}
class Dog extends Animal {
@Override
public String getSound() {
return 'Woof';
}
}
class Cat extends Animal {
@Override
public String getSound() {
return 'Meow';
}
}
public class Main {
public static void main(String[] args) {
Animal dog = new Dog();
Animal cat = new Cat();
System.out.println(dog.getSound()); // Output: Woof
System.out.println(cat.getSound()); // Output: Meow
}
}
在上述例子中,子类 Dog 和 Cat 分别重写了父类 Animal 的 getSound() 函数,并返回了不同的字符串。当通过父类 Animal 的引用指向子类对象时,调用 getSound() 函数时会根据对象的实际类型执行相应的子类方法,实现多态。
原文地址: https://www.cveoy.top/t/topic/pTwY 著作权归作者所有。请勿转载和采集!