zoukankan      html  css  js  c++  java
  • 浅谈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)时,编译器就会报错,说明语法上是不允许这么操作的。

  • 相关阅读:
    记录一下idea自动生成Entity
    Spring-boot之 swagger2
    Spring-boot之 rabbitmq
    Js 跳出两级循环的方法
    Activiti 工作流变量的修改方法
    Spring-boot(二)yml文件的使用
    Spring-boot初始化创建(一)
    数据库性能优化:程序操作优化
    数据库性能优化:数据库表优化
    数据库性能优化:数据库自身优化
  • 原文地址:https://www.cnblogs.com/hushunfeng/p/3930164.html
Copyright © 2011-2022 走看看