抽象类是用abstract
关键字定义的类,在类的声明中使用abstract
修饰符。
接口是用interface
关键字定义的接口,在接口的声明中使用interface
关键字。
implements
关键字实现接口。抽象类和接口都不能被实例化,它们只能被子类或实现类继承或实现,并通过子类或实现类的实例化对象来调用其方法。
下面是抽象类和接口的定义和语法的示例:
// 抽象类的定义
abstract class Animal {
String name;
// 抽象方法
abstract void sound();
// 具体方法
void eat() {
System.out.println(name + " is eating");
}
}
// 接口的定义
interface Shape {
void draw(); // 抽象方法
int calculateArea(); // 抽象方法
double PI = 3.1415; // 常量
}
// 抽象类的继承
class Dog extends Animal {
void sound() {
System.out.println(name + " is barking");
}
}
// 接口的实现
class Circle implements Shape {
int radius;
public void draw() {
System.out.println("Drawing a circle");
}
public int calculateArea() {
return (int) (PI * radius * radius);
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.name = "Tom";
dog.sound();
dog.eat();
Circle circle = new Circle();
circle.draw();
circle.calculateArea();
}
}
在上面的代码中,Animal
抽象类定义了一个抽象方法sound()
和一个具体方法eat()
。Dog
类继承了Animal
抽象类,并实现了抽象方法。Shape
接口定义了两个抽象方法draw()
和calculateArea()
,以及一个常量PI
。Circle
类实现了Shape
接口,并实现了接口的抽象方法。通过main
方法中的代码来实例化和调用。
下面是一个代码实例来说明接口和抽象类的区别:
// 接口定义
interface Shape {
void draw(); // 抽象方法,没有具体实现
int calculateArea(); // 抽象方法,没有具体实现
double PI = 3.1415; // 常量
}
// 抽象类定义
abstract class Animal {
String name; // 成员变量
abstract void sound(); // 抽象方法,没有具体实现
void eat() { // 具体方法
System.out.println(name + " is eating");
}
}
// 类继承接口和抽象类
class Circle implements Shape {
int radius;
public void draw() {
System.out.println("Drawing a circle");
}
public int calculateArea() {
return (int) (PI * radius * radius);
}
}
class Dog extends Animal {
void sound() {
System.out.println(name + " is barking");
}
}
public class Main {
public static void main(String[] args) {
Circle circle = new Circle();
circle.draw();
circle.calculateArea();
Dog dog = new Dog();
dog.name = "Tom";
dog.sound();
dog.eat();
}
}
在上面的代码中,Shape
接口定义了两个抽象方法draw()
和calculateArea()
,以及一个常量PI
。Circle
类实现了Shape
接口,并实现了接口的抽象方法。Animal
抽象类定义了一个抽象方法sound()
和一个具体方法eat()
,Dog
类继承了Animal
抽象类,并实现了抽象方法。通过main
方法中的代码来实例化和调用。