多态是设计上的一个术语。(polymorphism)
在Java里,多态是指以下语法现象:
重载OVerload:方法允许重名;
重写Override:允许子类重写父类方法;
泛型(模版):比如ArryList;
子类与父类的类型转换
1.子类转成父类:
ApplePie p1=new ApplePie();
Pie p2=p1; //类型转换:ApplePie->Pie
2.父类转成子类类型:
ApplePie p3=(ApplePie)p2;
注意:这个有时可以,有时不可以,这里可以是因为p2实际指向的对象是ApplePie,所以可以转换。
如何理解多态
Human.java
在Java里,多态是指以下语法现象:
重载OVerload:方法允许重名;
重写Override:允许子类重写父类方法;
泛型(模版):比如ArryList;
子类与父类的类型转换
1.子类转成父类:
ApplePie p1=new ApplePie();
Pie p2=p1; //类型转换:ApplePie->Pie
2.父类转成子类类型:
ApplePie p3=(ApplePie)p2;
注意:这个有时可以,有时不可以,这里可以是因为p2实际指向的对象是ApplePie,所以可以转换。
如何理解多态
如下所示:
Child.java
package my;
public class Child extends Human
{
int a;
int b;
public void information() {
System.out.println("The Child a is "+a+", b is "+b);
}
}
package my;
public class HelloWorld
{
public static void main(String[] args)
{
Child a=new Child();
Human b=a;
a.information();
b.information();
Human c=new Child();
c.information();
Object d=new Human();
}
}
Human.java
package my;
public class Human
{
public int weight;
public int height;
public void information() {
System.out.println("Human weight is "
+weight+", height is "+height);
}
}
所有对象都是Object
所以:Object x=new MyVideoFile()