Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

java抽象类

作者:最终一次颓废   发布日期:2026-04-22   浏览:84

// 定义一个抽象类 Animal
abstract class Animal {
    // 抽象方法,子类必须实现
    public abstract void makeSound();

    // 普通方法,子类可以直接继承或重写
    public void eat() {
        System.out.println("This animal is eating.");
    }
}

// 继承抽象类 Animal 的具体类 Dog
class Dog extends Animal {
    // 实现抽象方法 makeSound
    public void makeSound() {
        System.out.println("Dog says: Woof!");
    }
}

// 继承抽象类 Animal 的具体类 Cat
class Cat extends Animal {
    // 实现抽象方法 makeSound
    public void makeSound() {
        System.out.println("Cat says: Meow!");
    }
}

// 测试类
public class TestAbstractClass {
    public static void main(String[] args) {
        // 创建 Dog 和 Cat 对象
        Animal myDog = new Dog();
        Animal myCat = new Cat();

        // 调用 makeSound 方法
        myDog.makeSound(); // 输出: Dog says: Woof!
        myCat.makeSound(); // 输出: Cat says: Meow!

        // 调用 eat 方法
        myDog.eat(); // 输出: This animal is eating.
        myCat.eat(); // 输出: This animal is eating.
    }
}

解释说明:

  1. 抽象类 Animal:定义了一个抽象方法 makeSound() 和一个普通方法 eat()。抽象方法没有具体的实现,必须由子类实现。
  2. 具体类 DogCat:继承了抽象类 Animal,并实现了抽象方法 makeSound()
  3. 测试类 TestAbstractClass:创建了 DogCat 对象,并调用了它们的 makeSound()eat() 方法。

通过这种方式,抽象类提供了一种模板机制,允许子类根据需要实现特定的行为。

上一篇:java contains

下一篇:java transient

大家都在看

java url decode

java判断是windows还是linux

java连接数据库的代码

java date类型比较大小

java djl

ubuntu 卸载java

es java api

java list 查找

java 解压rar

jsonobject.tojavaobje

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站