一:多态性
1.父类
2.子类
如果属性重名,会打印父类的
二:向下转型的使用
那么如何才能调用子类特有的属性和方法呢?
使用强制类型转换符也就是向下转型
注意:
所以我们要使用instanceof
Person.java
package com.xx.study1028;
public class Person {
String name;
int age;
public void eat() {
System.out.println("吃饭");
}
public void sleep() {
System.out.println("睡觉");
}
public void walk() {
System.out.println("人能走路");
}
}
Man.java
package com.xx.study1028;
public class Man extends Person {
boolean isSomking;
public void sport() {
System.out.println("喜欢打篮球");
}
public void eat() {
System.out.println("吃肉");
}
public void walk() {
System.out.println("不爱走路");
}
}
Woman.java
package com.xx.study1028;
public class Woman extends Person{
boolean isBeauty;
public void goShopping() {
System.out.println("喜欢购物");
}
public void eat() {
System.out.println("喜欢吃蔬菜");
}
public void walk() {
System.out.println("喜欢走路");
}
}
PersonTest.java
package com.xx.study1028;
import com.xx.study.Student;
public class PersonTest {
public static void main(String[] args) {
Person p1=new Person();
p1.eat();
Man man=new Man();
man.eat();
man.age=24;
man.sport();
System.out.println("************************");
//对象的多态性:父类的引用指向子类的对象
Person p2=new Man();
Person p3=new Woman();
//多态的使用,当调用子父类同名参数的方法时,实际执行的是子类重写父类的方法————————虚拟方法调用
p2.eat();
p2.walk();
//结论:不能调用子类所特有的方法,属性。编译时,p是Person类型
//p1.isSomking=true;不能调用
//有了对象的多态性后,内存中实际上是加载了子类特有的属性和方法,但是由于变量声明为父类类型
//导致编译时,只能调用父类中声明的属性和方法,子类特有的属性和方法不能调用
//如何调用子类特有的属性和方法?使用强转 m
Man m1=(Man)p2;//p转为Man
m1.isSomking=true;
//instanceof 关键字的使用
if(p2 instanceof Woman) {
Woman w1=(Woman)p2;
w1.eat();
System.out.println("woman");
}
if(p2 instanceof Man) {
Man m2=(Man)p2;
m2.eat();
System.out.println("man");
}
//如果a instanceof A返回true,则a instanceof B也返回true 其中类B是类A的父类
if(p2 instanceof Person) {
System.out.println("Person");
}
if(p2 instanceof Object) {
System.out.println("Object");
}
}
}