前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Java 抽象类、接口

Java 抽象类、接口

作者头像
Michael阿明
发布2021-09-06 10:01:23
4860
发布2021-09-06 10:01:23
举报
文章被收录于专栏:Michael阿明学习之路
  • abstract class

抽象类定义规则如下:

(1) 抽象类和抽象方法都必须用 abstract 关键字来修饰。 (2) 抽象类不能被直接实例化,也就是不能用new关键字去产生对象。 (3) 抽象方法只需声明,而不需实现。 (4) 含有抽象方法的类必须被声明为抽象类,抽象类的子类必须覆写所有的抽象方法才能被实例化,否则这个子类还是抽象的

代码语言:javascript
复制
abstract class Person2 { // 抽象类
    String name;
    int age;
    String occupation;
    public abstract void talk();
    public Person2(String name, int age, String occupation)
    {
        this.name = name;
        this.age = age;
        this.occupation = occupation;
    }
}

class Student1 extends Person2
{
    public Student1(String name, int age, String occupation)
    {
        // 必须明确调用 抽象类的构造方法
        super(name, age, occupation);
    }

    // 要实例化, 必须 覆写 抽象方法 talk
    public void talk()
    {
        System.out.println("覆写talk()");
    }
}

class test2{
    public static void main(String[] args)
    {
        Student1 s = new Student1("Ming", 18, "student");
        s.talk();
    }
}
  • interface 接口 数据成员全部是常量 final 初始化 所有方法全部是 abstract 抽象的,没有一般方法

Java 没有多重继承,但是可以使用 接口 来实现 多继承 class 类名 implements 接口A, 接口B

接口 可以继承于 多个 接口 interface 接口C extends 接口A, 接口B

代码语言:javascript
复制
// 接口
// 数据成员全部是常量 final 初始化
// 所有方法全部是 abstract
interface Person3 {
    final String name = "Michael"; // 必须初始化,final 可省略
    int age = 18;
    String occupation = "工程师";
    public abstract void talk1(); // abstract 可省略
}
interface Worker1{
    String tool = "hammer";
}

// 类可以实现多个接口
class Student2 implements Person3, Worker1
{
    // 要实例化,必须覆写 talk
    public void talk1()
    {
        System.out.println("name: " + this.name + ", age: " + this.age
                        + ", occupation: " + this.occupation
                        + ", tool: " + this.tool);
    }
}

// 接口可以继承于多个接口 (类的继承只能继承1个父类)
interface AnotherInterface extends Person3, Worker1
{
    String state = "person3+worker1";
    public void talk2();//抽象方法
}

class Student3 implements AnotherInterface{
    // Student3 要实现 Person3, Worker1, AnotherInterface 3个接口
    public void talk1(){
        System.out.println("每个抽象方法要覆写,talk1()");
    }
    public void talk2(){
        System.out.println("每个抽象方法要覆写,talk2()");
    }
}
class test3
{
    public static void main(String[] args){
        Student2 s2 = new Student2();
        s2.talk1();

        Student3 s3 = new Student3();
        s3.talk1();
        s3.talk2();
    }
}

输出:

代码语言:javascript
复制
name: Michael, age: 18, occupation: 工程师, tool: hammer
每个抽象方法要覆写,talk1()
每个抽象方法要覆写,talk2()
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021/02/25 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档