JAVA中向上转型的问题
比如我这个程序
public class Testjava{
public static void main(String args[])
{
fun(new Student());
fun(new Allen());
}
public static void fun(Person p)
{
p.fun2();
if (p instanceof Student)
{
Student s=(Student)p;
s.fun3();
}
if (p instanceof Allen)
{
Allen a=(Allen)p;
a.fungod();
}
}
}
fun3()和fungod()分别是Student类和Allen类里面的方法,我想调用他们的时候为什么要向上转型呢,感觉没什么意义,直接写Student s=new Student()和Allen a=new Allen()各建立一个新对象再调用他们各自特有的方法不就可以了吗?可否详细解释向上转型在JAVA中的意义。我是自学的,麻烦解释详细一点,拜托大家了~~
答案:package test;
public class Test3 {
public static void main(String[] args) {
Person p = new Person();
Person s = new Student();
Person a = new Allen();
p.fun();
System.out.println("**********************");
s.fun();
System.out.println("**********************");
a.fun();
}
}
class Person{
void fun(){
System.out.println("I am a person!!!");
}
}
class Student extends Person{
void fun(){
super.fun();
System.out.println("I am a student!!!");
}
}
class Allen extends Person{
void fun(){
super.fun();
System.out.println("I am Allen!!!");
}
}
这就是一个上转型的例子,不同的实例,父类对象会自动调用对象对应具体子类的方法。可以实现多态。
比如:
void play(Person p){
p.fun();
}
这个方法里的参数可以是Person和它的子类的对象,调用的方法也是子类的方法。
有不懂的地方可以问我哦!(^_^)
其他:你为了调用父类的方法再去new一个对象方便 还是向上转型方便? 向上转型是为了提供统一的函数接口,调用函数public static void fun(Person p)时,不用分别写成两个不同参数类型的函数,这也是实现多态的基本方法。
上一个:哪位知道myeclipse里面的这怎么去掉(下图)
下一个:请问jfreechart生成的图片 在 websphere 上默认是放在什么地方在啊 我没有看见,但是在网页上可以显示