在Java中,子类可以通过继承父类和实现接口来扩展功能。以下是子类接口实现的步骤:
public interface MyInterface {
void interfaceMethod();
}
public class ParentClass {
public void parentMethod() {
System.out.println("This is a method in the parent class.");
}
}
public class SubClass extends ParentClass implements MyInterface {
@Override
public void interfaceMethod() {
System.out.println("This is the implementation of the interface method in the subclass.");
}
}
在这个例子中,SubClass 继承了 ParentClass 并实现了 MyInterface 接口。子类需要实现接口中定义的所有方法,这里是 interfaceMethod()。
public class Main {
public static void main(String[] args) {
SubClass subClass = new SubClass();
subClass.parentMethod(); // 调用父类的方法
subClass.interfaceMethod(); // 调用接口的方法
}
}
输出结果:
This is a method in the parent class.
This is the implementation of the interface method in the subclass.
这样,子类就成功地继承了父类并实现了接口。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。