向上转型向下转型


Java面向对象
完整代码

向上转型

**目的:**将子类对象转换成父类类型 使父类可以调用子父类中共有的函数
形式如下:
父类 变量名 = new 子类对象;
父类类型可以接收子类对象
//上面的示例便是使用了向上转型

//医生对象转换成了父类类型 父类可以调用子类中被重写的函数
Doctors zhanghui = new Doctors();
Person person = zhanghui;
person.Summon();

注重点:
☀ 向上转型 父类中与子类成员变量名相同 输出成员变量 调用的是父类的成员变量
☀ 向上转型 调用父类子类共有的属性和方法 不能调用特有的
☀ 当子类进行方法的重写后,调用的是子类的重写后的方法

instanceof

作用:对对象进行比较 同一对象类型返回true 不同返回false
实例

Doctors zhanghui = new Doctors();
Person person = zhanghui;
person instanceof Eunuch;//将返回false
person instanceof Doctors;//将返回true

向下转型

目的: 实现对子类对象特定方法的调用
使用过程
先进行向上转型

Doctors zhanghui = new Doctors();
Person person = zhanghui;

然后进行向下转型

//向上转型
Doctors zhanghui = new Doctors();
Person person = zhanghui;

//向下转型
Doctors doctors = (Doctors)person;
doctors.cure();//调用医生的特定方法

整个过程实现的是使用Person父类可以接受所有子类的对象 通过对子类对象的判断来确定子类对象的类型 进行强制转换 接收子类对象的信息 然后调用子类对象的特有方法完成相关需求
因此向下转型前提必须要先向上转型 才能实现

使用示例:
需求:后宫既然是为皇帝服务的 那么每个人都有特定的服务方向 比如太医治病 太监养马 妃子侍寝等等 我们可以使用多态和向下转型来完成整个需求

妃子侍寝

	//侍寝
	public void waiter() {
    
    
		System.out.println(name+"正在给皇帝侍寝");		
	}

太监养马

	//养马方法
	public void raiseHorses() {
    
    
		 System.out.println(name+"正在给皇上养马!");
	}

太医治病

	public void cure() {
    
    
		System.out.println(name+"正在给皇上治病");
	}
	

服务方法

	//向下转型 实现对子类特有方法的调用
	//服务方法
	public void  service(Person person) {
    
    
		if(person instanceof Eunuch) {
    
    
			Eunuch eunuch = (Eunuch) person;
			eunuch.raiseHorses();
		}else if(person instanceof WifeConcubine) {
    
    
			WifeConcubine wifeConcubine = (WifeConcubine) person;
			wifeConcubine.waiter();
		}else if(person instanceof Doctors) {
    
    
			Doctors doctors = (Doctors)person;
			doctors.cure();
		}else {
    
    
			
		}

测试类

		//多态测试  妃子 医生 宦官对象在上面皆以创建
		//WifeConcubine  lingfei = new WifeConcubine("季凌菲");
		//	Doctors zhanghui = new Doctors();
		//	Eunuch lihei = new Eunuch();
		
		Emperor emperor = new Emperor();
		System.out.println("向上转型");	
		emperor.ESummon(lingfei);
		emperor.ESummon(zhanghui);
		emperor.ESummon(lihei);
		
		System.out.println("向下转型");
		emperor.service(lingfei);
		emperor.service(zhanghui);
		emperor.service(lihei);

控制台输出
在这里插入图片描述

文章是作者面向对象文章的单独拆分如果存在阅读不连续性请参考下文

Java面向对象
完整代码

猜你喜欢

转载自blog.csdn.net/Carryi/article/details/119719004