在Java中,抽象类和接口都可以被声明使用,但是它们有不同的用途和语法规则

1、抽象类(Abstract Class)

抽象类是通过abstract关键字声明的类。
抽象类可以包含抽象方法和具体方法。
抽象类的主要目的是为了被子类继承,并且子类需要实现抽象方法。
抽象类可以有构造方法,但是不能被实例化。
可以使用抽象类的引用来引用其子类的对象。
示例:

abstract class Animal {
    abstract void makeSound();
    void sleep() {
        System.out.println("Zzz");
    }
}

class Dog extends Animal {
    void makeSound() {
        System.out.println("Woof");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal myDog = new Dog();
        myDog.makeSound(); // Output: Woof
        myDog.sleep(); // Output: Zzz
    }
}

2、 接口(Interface)

接口是通过interface关键字声明的。
接口只能包含常量和抽象方法。
接口的主要目的是定义一种契约,实现类需要遵守这个契约(即实现接口中定义的方法)。
一个类可以实现多个接口。
接口中的方法默认是public和abstract的,可以省略这些修饰符。
示例:

interface Animal {
    void makeSound();
    void eat();
}

class Dog implements Animal {
    public void makeSound() {
        System.out.println("Woof");
    }
    public void eat() {
        System.out.println("Dog eats");
    }
}

public class Main {
    public static void main(String[] args) {
        Dog myDog = new Dog();
        myDog.makeSound(); // Output: Woof
        myDog.eat(); // Output: Dog eats
    }
}
  • 8
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值