java基础复习 4 | 多态的简单理解

多态分为两种

1 编译时多态

  • 编译期间决定目标方法
  • 通过重载实现
  • 方法名相同,参数不同

先说第一种具体代码实现:

public class Demo3 {
	public int add(int a, int b) {
		return a + b;
	}

	public int add(int a, int b, int c) {
		return a + b + c;
	}
	public static void main(String[] args) {
		Demo3 d=new Demo3();
		System.out.println(d.add(1, 2));
		System.out.println(d.add(1, 2, 3));
	}
}

第二种具体代码实现:

2 运行时多态

  • 运行期间决定目标方法
  • 同名同参
  • 重写和继承实现
  • JVM决定目标方法
public class Demo3 {
	public static void main(String[] args) {
		Person a = new Person();
		a.run();
		Person b = new Man();
		b.run();
		Person c = new Woman();
		c.run();
	}
}

class Person {
	public void run() {
		System.out.println("人会跑");
	}
}

class Man extends Person {
	public void run() {
		System.out.println("男人会跑");
	}
}

class Woman extends Person {
	public void run() {
		System.out.println("女人会跑");
	}
}

第二种多态需要注意一个向上转型和向下转型

向上转型:
就是所谓的 父类引用指向子类对象
  
  //父类类型 变量名 = new 子类类型(); 
	Person b = new Man();
		b.run();
	Person c = new Woman();
		c.run();
向下转型:
父类类型向子类类型向下转换的过程,这个过程是强制的。

我们可以把向上转型和向下转型看成是基本数据类型转换。
在这里插入图片描述
向下转型的前提是父类对象指向的是子类对象(也就是说,在向下转型之前,它得先向上转型)

向下转型主要用于想要调用子类特有的方法

看以下代码:

public class Demo3 {
	public static void main(String[] args) {
		Person a = new Person();
		a.run();
		Person b = new Man();
		b.run();
		Man c =(Man)b;
		c.runfast();
	}
}

class Person {
	public void run() {
		System.out.println("人会跑");
	}
}

class Man extends Person {
	public void run() {
		System.out.println("男人会跑");
	}
	public void runfast() {
		System.out.println("男人跑得快");
	}
}
在这个代码中我把Man类特有的方法通过向下转型的方式调用了出来。

向下转型需要注意:

如果两个类型并没有任何继承关系,而进行转换的话,就会抛出一个 ClassCastException ,类型转换异常的错误。

看下面代码:


public class Demo3 {
	public static void main(String[] args) {
		Person a = new Person();
		a.run();
		Person b = new Man();
		Woman g = (Woman) b; //两个类型没有任何继承关系

	}
}

class Person {
	public void run() {
		System.out.println("人会跑");
	}
}

class Man extends Person {
	public void run() {
		System.out.println("男人会跑");
	}
}

class Woman extends Person {
	public void run() {
		System.out.println("女人会跑");
	}
}

运行结果直接就抛出:
在这里插入图片描述
为了让向下转型结果不抛出异常,我们使用 instanceof 关键字
转换前,我们先使用instanceof 先做一个判断


public class Demo3 {
	public static void main(String[] args) {
		Person b = new Man();
		if(b instanceof Man) { //进行判断
			Man g=(Man)b;
			g.run();
		}else if(b instanceof Woman) {
			Woman g=(Woman)b;
			System.out.println("---------");
		}
		
	}
}

class Person {
	public void run() {
		System.out.println("人会跑");
	}
}

class Man extends Person {
	public void run() {
		System.out.println("男人会跑");
	}
}

class Woman extends Person {
	public void run() {
		System.out.println("女人会跑");
	}
}

在这里插入图片描述
这次的运行结果就没有抛出异常了!
如有错误请指出~

发布了11 篇原创文章 · 获赞 0 · 访问量 168

猜你喜欢

转载自blog.csdn.net/weixin_44824500/article/details/104422655
今日推荐