您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
在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.
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。