1、instanceof关键词
A instanceof B是用来判断内存中的实际对象A是不是B类型(具体事例看3小节代码)
2、重写条件:
1、继承关系
2、子类重写父类方法
3、方法名一样,参数个数和类型一样
3、继承
子类Student继承父类Person,实例化子类对象student的时候,在堆中会为其分配内存空间,在其内存空间中再划分一部分空间作为实例化一个父类new Person()的内存空间,这个父类对象的属性方法只为子类对象student服务
装箱和拆箱
public class Person {
String name;
}
public class Student extends Person{
int height;
public void study() {
System.out.println("学习");
}
}
public class Test05 {
public static void main(String[] args) {
Person p = new Person();
Student s = new Student();
//instanceof可用于if判断中
System.out.println(p instanceof Person); //true
System.out.println(s instanceof Student); //true
System.out.println(s instanceof Person); //true
System.out.println(p instanceof Student); //false
//装箱
//当把Student对象赋值给Person类型引p1时,p1指向Student对象地址,但引用p1只能找到(识别)Person中自带的属性和方法
Person p1 = s;
//下面这个写法其实和上面的Person p1 = s;是一个意思
Person p2 = new Student();
//拆箱
//再把父类强制转换为子类(前提是:首先要有一个子类对象赋值给父类的引用)
//s2指向对象p1地址,但是由于p1指向的是Student对象地址,所以s2指向的是Student对象地址,引用s2是Student类型可以找到Person和Student中自带的属性和方法
Student s2 = (Student)p1;
//注意:并不能直接把父类强制转换为子类
//Student s3 = (Student)p;
System.out.println(p1 instanceof Person); //true
System.out.println(p1 instanceof Student); //true
System.out.println(p2 instanceof Person); //true
System.out.println(p2 instanceof Student); //true
}
}
4、多态
面向对象三大特性:封装、继承、多态
多态存在的三个条件:
1、子类继承父类
2、子类重写父类方法
3、父类的引用指向子类的对象
小男孩玩宠物
拆箱装箱简单实例:
public class Boy {
/**
* Pet类、Bird类、Pig类 装箱拆箱
* @param p
*/
public void play(Pet p) {
if(p instanceof Bird) {
Bird d = (Bird) p;
d.birdEnjoy();
}else if(p instanceof Pig) {
Pig pig = (Pig) p;
pig.pigEnjoy();
}
}
}
//宠物类
public class Pet {
public void enjoy() {
System.out.println("叽叽叽叽~~~宠物很高兴");
}
}
//小猪类
public class Pig extends Pet{
public void pigEnjoy() {
System.out.println("哼哼哼哼~~~~小猪很高兴!");
}
}
//小鸟类
public class Bird extends Pet{
public void birdEnjoy() {
System.out.println("叽叽叽叽~~~鸟儿很高兴");
}
}
public class BoyFun {
public static void main(String[] args) {
Boy boy = new Boy();
Bird b = new Bird();
Pig p = new Pig();
boy.play(b);
boy.play(p);
}
}
运行:
叽叽叽叽~~~鸟儿很高兴
哼哼哼哼~~~~小猪很高兴!
多态简单实例:
public class Boy {
public void play(Pet p) {
p.enjoy();
}
}
//宠物类
public class Pet {
public void enjoy() {
System.out.println("叽叽叽叽~~~宠物很高兴");
}
}
//小猪类
public class Pig extends Pet{
public void enjoy() {
System.out.println("哼哼哼哼~~~~小猪很高兴!");
}
}
//小鸟类
public class Bird extends Pet{
public void enjoy() {
System.out.println("叽叽叽叽~~~鸟儿很高兴");
}
}
public class BoyFun {
public static void main(String[] args) {
Boy boy = new Boy();
Bird b = new Bird();
Pig p = new Pig();
boy.play(b);
boy.play(p);
}
}
运行:
叽叽叽叽~~~鸟儿很高兴
哼哼哼哼~~~~小猪很高兴!