代码1
package FirstPackage;
public class PolyMorphic {
public static void main(String[] args) {
// TODO Auto-generated method stub
Father a=new Son();
a.say();
System.out.println(a.age);
System.out.println(a.height);
a.printage();
a.sing();
}
}
class Father{
static int height=165;
public int age=46;
public void say()
{
System.out.println("I am father!");
}
public void printage()
{
System.out.println("father age is "+String.valueOf(age));
}
public static void sing() {
System.out.println("I am father!");
}
}
class Son extends Father{
static int height=175;
public int age=24;
public void say() {
System.out.println("I am son!");
}
public void printage()
{
System.out.println("son age is "+String.valueOf(age));
}
public static void sing() {
System.out.println("I am son!");
}
}
输出:
I am son!
46
165
son age is 24
I am father!
- 成员变量:编译看左边(父类),运行看左边(父类)
- 成员方法:编译看左边(父类) ,运行看右边(子类)!!!!
- 静态方法:编译看左边(父类) ,运行看左边(父类)
- 静态变量:编译看左边(父类),运行看左边(父类)
如果父类中没有定义say()方法
就会由于编译看左边而导致编译
打印输出就是运行看右边
代码2
其他部分同代码1
只改main()中
Father a=new Son();
// Son b=a;//cannot convert from Father to Son
Son b=(Son)a;
- 第一行叫做向上转型:父类引用指向子类对象
- 第三行叫做向下转型:子类引用指向父类对象
- 第二行说明向下转型需要强制转换
好处和弊端
- 好处:
提高了代码的维护性(继承保证)
eg:在父类改一个属性不用每个子类都改属性
提高代码的扩展性(多态保证)
eg:方法中使用父类为参数,来实现方法或者属性的调用,这个很常见
- 弊端
不能使用子类的特有属性和行为
- 多态注意事项
开发中创建对象的时候用父类引用指向子类对象比较常用
当作参数时候使用多态最好,因为扩展性强
- 我觉得用的最多的就是父类引用指向子类对象作为方法的参数
- 比如 function1(Father fa){}
代码3
package FirstPackage;
public class PolyMorphic2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
A a=new B();
a.show();
B b=new C();
b.show();
}
}
class A{
public void show(){
show2();
}
public void show2(){
System.out.println("我");
}
}
class B extends A{
public void show2(){
System.out.println("爱");
}
}
class C extends B{
public void show(){
super.show();
}
public void show2(){
System.out.println("妳");
}
}
输出:
爱
妳
- B没有show,所以先到A的show,然后跳到B的show2
- C有show,先到C的show,然后到A的show(因为B没有show),最后到C的show2