多态:
---一个对象的多种形态
实质:父类的引用指向子类对象
---前提:必须有继承或者是实现
class animal{}
class dog extends animal{}
main{
dog d = new dog(); //本态
animal dog = new dog(); //多态
}
注意:通过多态形式创建的对象,只能访问子父类共有的成员方法,运行结果为子类结果是子类特有的成员方法不能方法。
虚拟方法调用:
父类对象调用子类特有的方法
student s = new student(张三,100);
person p = new student(李四,200);
system.out.println(s.say());
system.out.println(p.say());
多态数组 — 在引用类型的数组中,使用多态形式存放对象。
eg:person[] person = {new person(张三, 32),
new student(李四, 21, 120, 90.0),
new student(王五, 22, 119, 91.5),
new teacher(刘老师, 35, 10, java ee),
new teacher(张老师, 11)};
多态参数 — 方法参数列表中的引用类型参数
instanceof运算符 — 判断一个对象是否为指定类型(形态)
强制类型转换 — 将对象从一种引用形态转换为另一种引用形态
对象关联:
一个对象中使用了另一个对象
一对一,一对多,多对一
class test4 {
public static void main(string[] args){
person p = new person(王五,50);
method(p);
student s = new student(张三,100);
method(s);
person p1 = new student(赵四,100);
method(p1);
}
public static void method(person p){
if (p instanceof student){
system.out.println(教师);
student s = (student)p;
system.out.println(本态方法调用:+p.say());
}else{
system.out.println(人);
}
system.out.println(p.say());
}
}
class person{
private string name;
private int age;
public person(){}
public person(string name,int age){
this.name = name;
this.age = age;
}
public string getname(){
return name;
}
public string say(){
return 姓名:+name+年龄:+age;
}
}
class student extends person{
private int id;
private double score;
public student(string name,int id){
this(name,20,id,98.5);
}
public student(string name,int age,int id,double score){
super(name,age);
this.id = id;
this.score = score;
}
public double getid(){
return id;
}
public string say(){
return super.say()+学号:+id+分数:+score;
}
}