您的位置:首页 > 编程语言 > Java开发

java多态性测试

2016-04-06 00:00 387 查看
Java多态性理解 - Jack204 - 博客园
http://www.cnblogs.com/jack204/archive/2012/10/29/2745150.html

Java学习之 多态 Polymorphism - 圣骑士wind - 博客园
http://www.cnblogs.com/mengdd/archive/2012/12/25/2832288.html

【源代码】 package 多态性测试; class A{ public String show(D obj){ return ("A and D"); } public String show(A obj){ return ("A and A"); } } class B extends A{ public String show(B obj){ return ("B and B"); } public String show(A obj){ return ("B and A"); } } class C extends B{} class D extends B{} public class 多态性测试 { public static void main(String[] args){ A a1 = new A(); A a2 = new B(); B b = new B(); C c = new C(); D d = new D(); System.out.println(a1.show(b)); //A and A
System.out.println(a1.show(c));    //没什么说的,只可能是 A and A
System.out.println(a1.show(d));     //A and D,No problem // A a2 = new B(); // 栈中的引用变量是A,堆中的实例变量是B。 // 将子类的实例,赋值给父类的引用。就是向上转型。 // 向上转型,在运行时,会遗忘子类对象中与父类对象中不同的方法。也会覆盖与父类中相同的方法--重写。(方法名,参数都相同) // 所以a2,可以调用的方法就是,A中有的,但是B中没有的方法,和B中的重写A的方法。 //向上转型的对象调用的是哪个类中的方法是由new后面的类名决定的。这里调用的是B中的方法,包括从父类继承的方法
System.out.println(a2.show(b));   //B and A
System.out.println(a2.show(c));   // B and A //当B继承A之后,实际上B中有3个方法 //public String show(B obj){ //return ("B and B"); //} //public String show(A obj){ //return ("B and A"); //} //public String show(D obj){ //return ("A and D"); //}
System.out.println(a2.show(d));    // A and D
System.out.println(b.show(b));     //B and B
System.out.println(b.show(c)); // B and B
System.out.println(b.show(d));      //A and D
} }






------------------------下面是C#版本的例子-----------------------------------



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LearningTest
{
class Program
{
static void Main(string[] args)
{
A a1 = new A();
A a2 = new B();
B b = new B();
C c = new C();
D d = new D();

Console.WriteLine(a1.show(b));
Console.WriteLine(a1.show(c));
Console.WriteLine(a1.show(d));

Console.WriteLine(a2.show(b));
Console.WriteLine(a2.show(c));
Console.WriteLine(a2.show(d));

Console.WriteLine(b.show(b));
Console.WriteLine(b.show(c));
Console.WriteLine(b.show(d));

Console.ReadLine();
}
}

class A
{
public String show(D obj)
{
return ("A and D");
}
public String show(A obj)
{
return ("A and A");
}
}
class B : A
{
public String show(B obj)
{
return ("B and B");
}
public String show(A obj)
{
return ("B and A");
}
}
class C : B { }
class D : B { }

}

执行结果:



评论:java默认直接开启多态(重写).而C#在需要abstract和override关键字。C++需要声明为virtual
而java不需要这些关键字,直接就是多态.这么做的弊端是
父类 fu = new 子类()
fu可是使用子类方法,但不能调用父类同名方法.但C#和C++是可以的

---------------------------关于C#中函数重写的介绍------------------------







内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: