package java_test;
import org.junit.Test;
/**
* Polymorphic 多态
* @author Administrator
*
*/
class Poly1{
void speak(){
System.out.print("speak1"+" ");
}
void sleep(){
System.out.print("sleep1"+" ");
}
}
class Poly2 extends Poly1 {
void speak(){
System.out.print("speak2"+" ");
}
void skip(){
System.out.print("skip"+" ");
}
}
class Polymorphic{
@Test
public static void main(String[] args){
Poly1 poly1 = new Poly2();
poly1.speak();
poly1.sleep();
//poly1.skip(); 报错
Poly2 poly2 = (Poly2)poly1;
poly2.skip();
poly2.sleep();
poly2.speak();
}
import org.junit.Test;
/**
* Polymorphic 多态
* @author Administrator
*
*/
class Poly1{
void speak(){
System.out.print("speak1"+" ");
}
void sleep(){
System.out.print("sleep1"+" ");
}
}
class Poly2 extends Poly1 {
void speak(){
System.out.print("speak2"+" ");
}
void skip(){
System.out.print("skip"+" ");
}
}
class Polymorphic{
@Test
public static void main(String[] args){
Poly1 poly1 = new Poly2();
poly1.speak();
poly1.sleep();
//poly1.skip(); 报错
Poly2 poly2 = (Poly2)poly1;
poly2.skip();
poly2.sleep();
poly2.speak();
}
}
输出:speak2 sleep1 skip sleep1 speak2
总结:
@1,继承
@2,覆盖
@3,父类引用指向子类对象