接口和抽象方法示例
接口
接口可以让不同的类实现相同的接口,从而以统一的方式调用不同类的方法,实现多态。
package com.example.demo1;// 定义一个动物接口
interface Animal {void makeSound();
}// 狗类实现 Animal 接口
class Dog implements Animal {@Overridepublic void makeSound() {System.out.println("汪汪汪");}
}// 猫类实现 Animal 接口
class Cat implements Animal {@Overridepublic void makeSound() {System.out.println("喵喵喵");}
}public class InterfaceExample {public static void main(String[] args) {Animal dog = new Dog();Animal cat = new Cat();dog.makeSound();cat.makeSound();}
}
抽象方法
抽象类中的抽象方法要求子类必须实现,以此确保子类具有特定的行为。
package com.example.demo1;// 定义一个抽象类 Shape
abstract class Shape {// 抽象方法,计算面积public abstract double area();
}// 圆形类继承 Shape 抽象类
class Circle extends Shape {private double radius;public Circle(double radius) {this.radius = radius;}@Overridepublic double area() {return Math.PI * radius * radius;}
}// 矩形类继承 Shape 抽象类
class Rectangle extends Shape {private double width;private double height;public Rectangle(double width, double height) {this.width = width;this.height = height;}@Overridepublic double area() {return width * height;}
}public class AbstractMethodExample {public static void main(String[] args) {Shape circle = new Circle(5);Shape rectangle = new Rectangle(4, 6);System.out.println("圆的面积: " + circle.area());System.out.println("矩形的面积: " + rectangle.area());}
}