码迷,mamicode.com
首页 > 编程语言 > 详细

浅谈java中的多态性

时间:2014-08-22 21:07:49      阅读:226      评论:0      收藏:0      [点我收藏+]

标签:blog   java   ar   div   代码   log   new   c   对象   

讲到多态,就必须牵扯到继承和接口。至于多态强大的功能,目前水平有限,暂时还没有很明显地体会到。

我们先看 多态+继承

package test;

public class Test {

	public static void main(String[] args) {
		A test = new B();
		test.testA(100);
	}

}

class A {
	int i = 0;
	void testA(int i) {
		this.i = i;
		System.out.println("i的值为:"+i);
	}
	void print() {
		System.out.println("此时i的值已经变为:"+i);
	}
}

class B extends A {
	void testA(int i) {
		System.out.println("hello,hushunfeng!!"+i);
	}
	void testA(String str) {
		System.out.println("hello,my girl!!"+str);
	}
	void testB(int i) {
		System.out.println(i);
	}
}

运行结果:hello,hushunfeng!!100

分析:A test = new B();就是一个多态的体现。test是B的对象的一个引用,而它的类型是A。当我们调用testA(int i)函数,如果B中覆盖了testA(int i),那么就调用B类中testA(int i)中的内容进行执行。如果B没有对testA(int i)进行覆盖,则调用A类中的testA(int i)进行运行。如下代码。

class B extends A {
	/*void testA(int i) {
		System.out.println("hello,hushunfeng!!"+i);
	}*/
	void testA(String str) {
		System.out.println("hello,my girl!!"+str);
	}
	void testB(int i) {
		System.out.println(i);
	}
}

那么运行结果为:i的值为:100

如果我们调用B中特有的testB(int i)时,编译器就会报错,说明语法上是不允许这么操作的。

浅谈java中的多态性

标签:blog   java   ar   div   代码   log   new   c   对象   

原文地址:http://www.cnblogs.com/hushunfeng/p/3930164.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!