java 多态 深入理解多态-隐藏-低调-伪装

多态

package Lesson01;

public class Demo001 {

	public static void main(String[] args) {
		/*
		 * 超人案例(深入理解多态-隐藏-低调-伪装)
		 * 
		 * 超人去美国找某某集团的老总谈生意 超人在别人面前,如果不说自己是超人,在别人面前表现的就是普通人 老总以为是谈小生意的,但实际是谈大生意
		 * 老总以为他不会飞,实际上他会飞去救人
		 */

		// 父类指向子类对象(多态)
		Person p = new SupperMan();
		p.fly();
		SupperMan sm = new SupperMan();
		sm.fly();
		
		SpiderMan sp1 = new SpiderMan();
		sp1.fly();
//		Person p1 = new Person();
//		SupperMan sm2 = (SupperMan) p1;
//		sm2.fly();
		
		
		test1(sm);
		test2(sp1);
		test(sm);
		test(sp1);
	}
	public static void test(Person per)
	{
		per.fly();
	}
	
	public static void test1(SupperMan sm) {
		sm.fly();
	}

	public static void test2(SpiderMan sm) {
		sm.fly();
	}

}


	// 普通人
	class Person {
		public void walk() {
			System.out.println("走....");
		}

		public void fly() {
			System.out.println("我是普通人,不会飞...");
		}
	}

	// 超人
	class SupperMan extends Person {
		public void fly() {
			System.out.println("超人飞去救人...");
		}
	}

		// 蜘蛛
	class SpiderMan extends Person{
		public void fly(){
			System.out.println("蜘蛛侠爬去救人...");
		}
	}
	
	

  

原文地址:https://www.cnblogs.com/2eggs/p/12365051.html