【java】类的多态、向上转型对象、instanceof操作符

多态

在Java中多态有两种体现:

  • 基于方法重载的多态
    方法的重载:指一个类内部存在同名的方法,这些方法的参数类型或个数不同。
  • 基于方法覆盖(重写)的多态
    方法的覆盖:指子类对父类方法的重新改写,子类方法的声明与父类完全相同 。
  • 对象的多态(上转型对象)

向上转型对象

向上转型对象

Person是Student的父类,

Person e = new Student();

1、一个引用类型变量如果声明为父类的类型,但实际引用的是子类的对象,那么该变量就不能再访问子类中添加的属性和方法。
在这里插入图片描述
如上图e对象无法访问Student类中的school属性。
属性是在编译时确定的,编译时e为Person类型,没有school成员变量,因而编译错误。

2、虚拟方法调用

public class Student extends Person{
	private String school;
	
	public void showInfo() {
		System.out.println("Student类的showInfo()");
	}
	public static void main(String[] args) {
		Student stu = new Student();
		stu.showInfo();//调用的Student中的showInfo()
		
		Person p = new Person();
		p.showInfo();//调用的Person中的showInfo()
		
		Person e = new Student();
		e.showInfo();调用的Student中的showInfo()
	}
}
public class Person {
	int age;
	String name;
	
	public void showInfo() {
		System.out.println("Penson类的showInfo()");
	}
}

其运行结果为:
在这里插入图片描述

分析:编译时e为Person类型,而方法的调用是在运行时确定的,所以调用的是Student里的showInfo()方法。

在这里插入图片描述

instanceof操作符

x instanceof A;

检验x是否为类A的对象,返回值为boolean型。

public class Student extends Person{
	private String school;
	
	public void showInfo() {
		System.out.println("Student类的showInfo()");
	}
	public static void main(String[] args) {
		Student stu = new Student();
		Person p = new Person();
		
		System.out.println(stu instanceof Person);//true
		System.out.println(p instanceof Person);//true
		System.out.println(p instanceof Student);//flase
		
		Person e = new Student();
		System.out.println(e instanceof Student);//true
		System.out.println(e instanceof Person);//true
	}
}

其运行结果为:
在这里插入图片描述

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值