1 多态性
(1)方法的重载和重写
(2)对象的多态性
2 对象的多态性:
(1)向上转型: 程序会自动完成
父类 父类对象 = 子类实例
(2)向下转型:强制类型转换
子类 子类对象 = (子类) 父类实例
3 案例代码:
package csdn.zyl.demo;
class A12{
public void tell1()
{
System.out.println("A12--tell1");
}
public void tell2()
{
System.out.println("A12--tell2");
}
}
class B1 extends A12{
public void tell1(){
System.out.println("B1--tell1");
}
public void tell3(){
System.out.println("B1--tell3");
}
}
public class DuoTaiDemo {
class A12{
public void tell1()
{
System.out.println("A12--tell1");
}
public void tell2()
{
System.out.println("A12--tell2");
}
}
class B1 extends A12{
public void tell1(){
System.out.println("B1--tell1");
}
public void tell3(){
System.out.println("B1--tell3");
}
}
public class DuoTaiDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
//向上转型
System.out.println("向上转型结果");
B1 b = new B1();
A12 a = b;
a.tell1(); //tell1 ()重写
a.tell2();
//向下 转型
System.out.println("向下转型结果");
A12 a1 = new B1();
B1 b1 = (B1)a1;
b1.tell1();
b1.tell2();
b1.tell3();
}
// TODO Auto-generated method stub
//向上转型
System.out.println("向上转型结果");
B1 b = new B1();
A12 a = b;
a.tell1(); //tell1 ()重写
a.tell2();
//向下 转型
System.out.println("向下转型结果");
A12 a1 = new B1();
B1 b1 = (B1)a1;
b1.tell1();
b1.tell2();
b1.tell3();
}
}
案例结果:
向上转型结果
B1--tell1
A12--tell2
向下转型结果
B1--tell1
A12--tell2
B1--tell3
4 多态性的使用:
package csdn.zyl.demo;
// 多态的应用
class A111{
public void tell1(){
System.out.println("A--tell1");
}
}
class B111 extends A111{
public void tell2(){
System.out.println("B--tell2");
}
}
class C111 extends A111{
public void tell3()
{
System.out.println("S--tell3");
}
}
class D111 extends A111
{
}
public class PolDemo {
// 多态的应用
class A111{
public void tell1(){
System.out.println("A--tell1");
}
}
class B111 extends A111{
public void tell2(){
System.out.println("B--tell2");
}
}
class C111 extends A111{
public void tell3()
{
System.out.println("S--tell3");
}
}
class D111 extends A111
{
}
public class PolDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
say(new B111());
say(new C111());
say(new D111());
}
public static void say(A111 a)
{
a.tell1();
}
}
// TODO Auto-generated method stub
say(new B111());
say(new C111());
say(new D111());
}
public static void say(A111 a)
{
a.tell1();
}
}
案例结果:
A--tell1
A--tell1
A--tell1