面试题答案
一键面试- 通过继承实现多态:
- 在Java中,子类继承父类,子类可以重写父类的方法。当通过父类类型的变量引用子类对象时,调用重写的方法会表现出多态性。
- 示例代码如下:
// 定义父类
class Animal {
public void makeSound() {
System.out.println("动物发出声音");
}
}
// 定义子类Dog继承Animal
class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("汪汪汪");
}
}
// 定义子类Cat继承Animal
class Cat extends Animal {
@Override
public void makeSound() {
System.out.println("喵喵喵");
}
}
// 测试类
public class PolymorphismTest {
public static void main(String[] args) {
Animal animal1 = new Dog();
Animal animal2 = new Cat();
animal1.makeSound();
animal2.makeSound();
}
}
- 在上述代码中,
Animal
是父类,Dog
和Cat
是子类,它们重写了Animal
类的makeSound
方法。通过Animal
类型的变量引用不同子类的对象,调用makeSound
方法时,实际执行的是子类重写后的方法,这就体现了多态。
- 通过接口实现多态:
- 接口定义了一组方法的签名,但没有实现。类实现接口时必须实现接口中的所有方法。不同的类实现同一个接口,通过接口类型的变量引用不同实现类的对象,调用接口方法时表现出多态性。
- 示例代码如下:
// 定义接口
interface Shape {
double getArea();
}
// 定义类Circle实现Shape接口
class Circle implements Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double getArea() {
return Math.PI * radius * radius;
}
}
// 定义类Rectangle实现Shape接口
class Rectangle implements Shape {
private double width;
private double height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
@Override
public double getArea() {
return width * height;
}
}
// 测试类
public class InterfacePolymorphismTest {
public static void main(String[] args) {
Shape shape1 = new Circle(5);
Shape shape2 = new Rectangle(4, 6);
System.out.println("圆形面积: " + shape1.getArea());
System.out.println("矩形面积: " + shape2.getArea());
}
}
- 在这段代码中,
Shape
是接口,Circle
和Rectangle
类实现了Shape
接口并实现了getArea
方法。通过Shape
类型的变量引用不同实现类的对象,调用getArea
方法时,实际执行的是对应实现类中的方法,体现了多态。
在模块化编程场景下,通过这样的继承和接口实现的多态,可以让代码结构更清晰,模块之间的耦合度降低,增强代码的可维护性和扩展性。例如在一个图形绘制模块中,可以将不同图形的绘制逻辑封装在各自的类中,通过接口统一调用,方便添加新的图形类型。