• 浅谈java中的多态性


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

    我们先看 多态+继承

    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)时,编译器就会报错,说明语法上是不允许这么操作的。

  • 相关阅读:
    hdu4911 简单树状数组
    hdu4911 简单树状数组
    hdu4912 LCA+贪心
    hdu4912 LCA+贪心
    hdu4907 水dp 或者set
    hdu4907 水dp 或者set
    hdu4908 中位数子串
    hdu4908 中位数子串
    hdu4909 状态压缩(偶数字符子串)
    hdu4909 状态压缩(偶数字符子串)
  • 原文地址:https://www.cnblogs.com/hushunfeng/p/3930164.html
Copyright © 2020-2023  润新知