Java Subclass子类接口实现方法

发布时间:2025-02-14 02:14:27 作者:小樊
来源:亿速云 阅读:90

在Java中,子类可以通过继承父类和实现接口来扩展其功能。以下是一个简单的示例,说明如何创建一个子类并实现一个接口。

首先,我们定义一个接口MyInterface

public interface MyInterface {
    void interfaceMethod();
}

接下来,我们创建一个父类ParentClass,它包含一些基本功能:

public class ParentClass {
    public void parentMethod() {
        System.out.println("This is a method in the parent class.");
    }
}

现在,我们创建一个子类ChildClass,它继承了ParentClass并实现了MyInterface接口:

public class ChildClass extends ParentClass implements MyInterface {

    @Override
    public void interfaceMethod() {
        System.out.println("This is the implementation of the interface method.");
    }

    public void childMethod() {
        System.out.println("This is a method in the child class.");
    }
}

在这个例子中,ChildClass继承了ParentClass的所有属性和方法,并实现了MyInterface接口的interfaceMethod()方法。此外,ChildClass还定义了一个名为childMethod()的新方法。

以下是如何使用ChildClass的示例:

public class Main {
    public static void main(String[] args) {
        ChildClass child = new ChildClass();
        
        // 调用继承自父类的方法
        child.parentMethod();
        
        // 调用实现接口的方法
        child.interfaceMethod();
        
        // 调用子类自己的方法
        child.childMethod();
    }
}

输出结果:

This is a method in the parent class.
This is the implementation of the interface method.
This is a method in the child class.
推荐阅读:
  1. 怎么调用java构造方法
  2. Java中final与继承操作实例分析

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java

上一篇:Java Subclass子类与父类关系探讨

下一篇:Java Subclass子类设计模式选择

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》