Java中的多态及实现示例
- 简介
 - 实现示例
 - instance of(待补)
 
补入Java多态
简介
【预留(业务逻辑)接口的抽象类】对象 = new 【实现了该 预留(业务逻辑)接口】的【预留业务逻辑接口的抽象类的子类】的 对象,详见下方实现示例所示。
Java多态实现的关键有二:
父类引用 = 子类对象,因为需要 父类引用 统一接收【各种子类】的对象 以实现多态。- 【赋值给父类引用的子类对象】所属类的定义中【要实现 其父类中预留(业务逻辑)接口的 方法】,父类中可以不实现该预留的接口方法。
 
有的场景将【子类需要实现的接口方法】作为构造函数的参数、调用方法的形参,其目的是为了强制使用者实现接口中的虚方法,以避免使用者的遗漏。
实现示例
//预留业务逻辑接口的抽象类
public class TestPolymorphicParent{
	protected TestInterface tI;
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		TestPolymorphicParent polymorphic = new TestPolymorphicChild();
		polymorphic.businessLogic();
	}
	
	protected void businessLogic() {
		System.out.println("第一步");
		if (tI!=null) {
			tI.unifiedMethodName();
		}
		System.out.println("第三步");
	}
}
 
//实现了该接口的类
public class TestPolymorphicChild extends TestPolymorphicParent{
	public TestPolymorphicChild() {
		// TODO Auto-generated constructor stub
		tI = new TestInterface() {
			
			@Override
			public void unifiedMethodName() {
				// TODO Auto-generated method stub
				System.out.println("第二步:由子类TestPolymorphicChild实现");
			}
		};
	}
}
 
运行结果,如下所示。
 
instance of(待补)
Java多态还可与 instance of 结合使用。【判断某个对象是否属于某种数据类型的instanceof关键字】
Father f1=new Daughter();
 Father f2=new Son();
 if(f1 instanceof Daughter){
 System.out.println(“f1是Daughter的类型”);
 }
















![vue老项目增加提交格式化功能[eslint+prettier+husky+lint-staged]](https://img-blog.csdnimg.cn/72865cbeb7f94ff0b43276a432a6baf1.png)


