java day09 多态
多态概述
- 多态前提
* 要有继承关系
* 要有方法重写
* 要有父类引用指向子类对象
class a {
public static void main(String[] args){
cat c=new cat();
c.eat();
animal a=new cat(); //父类引用指向子类对象
a.eat();
}
}
class animal {
public void eat(){
System.out.println("eat");
}
}
class cat extends animal { //继承
public void eat(){ //重写
System.out.println("cat eat");
}
}

- 成员变量的引用
class a {
public static void main(String[] args){
father f=new son();
System.out.println(f.num);
son s=new son();
System.out.println(s.num);
}
}
class father {
int num=10;
}
class son extends father{
int num=20;
}
结果输出10 20
- 成员方法的访问
class a {
public static void main(String[] args){
father f=new son();
f.print();
}
}
class father {
int num=10;
public void print(){
System.out.println("father");
}
}
class son extends father{
int num=20;
public void print(){
System.out.println("son");
}
}
结果输出 son
- 总结
- father f=new son();
- 成员变量:编译看左边(父类),运行看左边(父类);
- 成员方法(非静态):编译看左边(父类),运行看右边(子类);
来源:CSDN
作者:neymar1204
链接:https://blog.csdn.net/neymar1204/article/details/104125401