Home  >  Article  >  Java  >  Java polymorphic parent class calls method of subclass

Java polymorphic parent class calls method of subclass

黄舟
黄舟Original
2017-08-13 09:43:233397browse

package test1;

Java polymorphic parent class calls the method of the subclass

//多态的体现
import javax.print.attribute.standard.RequestingUserName;
import java.util.Scanner;
public class testfather {
public static void main(String[] args)
{
Animal a  = new fish();   //父类对象被赋以子类类型
/*Animal a;
fish b = new fish b;
a= b
;      //向上转型,不丢失精度
a.talk();*/       //可达到相同效果
a.talk();      //fish覆写animal talk方法
Animal c = new bird();
//C.talk2();    //不能实现,因为animal中没有此方法,必须向下转型
   bird b = (bird)c;    //如果不进行转换,父类无法看到子类新扩充的方法
   b.talk2();
}
}
class Animal
{
public void talk()    //如果父类方法不想被覆写,可改为public 
static
 void talk()
{
System.out.println("walk");
}
}
class fish extends Animal
{
public void talk()
{
System.out.println("swim");
}
}
class bird extends Animal
{
public void talk()
{
System.out.println("fly");
}
public void talk2()//父类中没有此方法,调用必须进行强制转换,向下转型。
{
System.out.println("i am a bird");
}
}

The above is the detailed content of Java polymorphic parent class calls method of subclass. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn