Java中implements和extends的实现
导言
在Java中,我们可以通过使用关键字implements
和extends
来实现类之间的继承和接口的实现。本文将详细介绍如何在Java中使用这两个关键字。
整体流程
下表展示了使用implements
和extends
的整个流程。
步骤 | 描述 |
---|---|
1. | 创建接口或父类 |
2. | 创建实现类或子类 |
3. | 实现接口或继承父类 |
4. | 覆写接口方法或父类方法 |
5. | 使用实现类或子类对象 |
下面将逐步介绍每个步骤所需做的事情,并提供相应的代码示例。
1. 创建接口或父类
在实现接口或继承父类之前,我们首先需要定义接口或父类。接口是一组方法的集合,而父类是其他类的基类。
以下是一个示例接口MyInterface
的定义:
public interface MyInterface {
void myMethod();
}
以下是一个示例父类MyClass
的定义:
public class MyClass {
public void myMethod() {
System.out.println("This is a method in the parent class.");
}
}
2. 创建实现类或子类
接下来,我们需要创建一个实现接口或继承父类的类。实现类将实现接口中定义的方法,而子类将继承父类中的方法。
以下是一个示例实现类MyClassImpl
的定义:
public class MyClassImpl implements MyInterface {
public void myMethod() {
System.out.println("This is a method in the implementation class.");
}
}
以下是一个示例子类MySubClass
的定义:
public class MySubClass extends MyClass {
// 子类可以添加新的方法或覆写父类方法
public void mySubMethod() {
System.out.println("This is a method in the subclass.");
}
}
3. 实现接口或继承父类
在实现类中,我们使用implements
关键字来实现接口,而在子类中,我们使用extends
关键字来继承父类。
以下是在实现类中实现接口的示例代码:
public class MyClassImpl implements MyInterface {
// 实现接口的方法
public void myMethod() {
System.out.println("This is a method in the implementation class.");
}
}
以下是在子类中继承父类的示例代码:
public class MySubClass extends MyClass {
// 子类可以添加新的方法或覆写父类方法
public void mySubMethod() {
System.out.println("This is a method in the subclass.");
}
}
4. 覆写接口方法或父类方法
如果在实现接口时,我们需要在实现类中覆写接口中定义的方法。同样,如果在继承父类时,我们可以选择覆写父类中的方法。
以下是在实现类中覆写接口方法的示例代码:
public class MyClassImpl implements MyInterface {
// 实现接口的方法
public void myMethod() {
System.out.println("This is a method in the implementation class.");
}
}
以下是在子类中覆写父类方法的示例代码:
public class MySubClass extends MyClass {
// 覆写父类的方法
public void myMethod() {
System.out.println("This is a method in the subclass.");
}
}
5. 使用实现类或子类对象
最后,我们可以使用实现类或子类的对象来调用相应的方法。
以下是使用实现类对象的示例代码:
MyInterface obj = new MyClassImpl();
obj.myMethod(); // 输出: This is a method in the implementation class.
以下是使用子类对象的示例代码:
MySubClass obj = new MySubClass();
obj.myMethod(); // 输出: This is a method in the subclass.
obj.mySubMethod(); // 输出: This is a method in the subclass.
类图
下面是上述示例中的类