abstract Java

java中的abstract怎么使用

小亿
95
2023-08-30 01:08:01
栏目: 编程语言

在Java中,abstract是一个关键字,用于修饰类、方法和接口。

  1. 修饰类:

示例:

public abstract class Animal {
public abstract void makeSound();
public void sleep() {
System.out.println("Animal is sleeping");
}
}
public class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("Dog is barking");
}
}
public class Main {
public static void main(String[] args) {
Animal dog = new Dog();
dog.makeSound(); // 输出 "Dog is barking"
dog.sleep(); // 输出 "Animal is sleeping"
}
}
  1. 修饰方法:

示例:

public abstract class Animal {
public abstract void makeSound();
public void sleep() {
System.out.println("Animal is sleeping");
}
}
public class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("Dog is barking");
}
}
public class Main {
public static void main(String[] args) {
Animal dog = new Dog();
dog.makeSound(); // 输出 "Dog is barking"
}
}
  1. 修饰接口:

示例:

public interface Animal {
void makeSound();
}
public class Dog implements Animal {
@Override
public void makeSound() {
System.out.println("Dog is barking");
}
}
public class Main {
public static void main(String[] args) {
Animal dog = new Dog();
dog.makeSound(); // 输出 "Dog is barking"
}
}

总结:

abstract关键字用于定义抽象类、抽象方法和接口,通过使用abstract关键字,可以使类、方法和接口具有抽象的特性,需要在子类中进行实现。

0
看了该问题的人还看了