黑马程序员——面向对象-多态

------Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------

 

    这个多态的图片要小很多,应该可以有很好的效果。

 

果然清晰明了!!!

 

多态的小例子:

abstract class Animal {
	abstract void eat();

}

class Dog extends Animal {
	void eat() {
		System.out.println("啃骨头");
	}

	void lookHome() {
		System.out.println("看家");
	}
}

class Cat extends Animal {
	void eat() {
		System.out.println("吃鱼");
	}

	void catchMouse() {
		System.out.println("抓老鼠");
	}
}

class Pig extends Animal {
	void eat() {
		System.out.println("饲料");
	}

	void gongDi() {
		System.out.println("拱地");
	}
}

class DuoTaiDemo {
	public static void main(String[] args) {

		// Cat c = new Cat();
		// c.eat();
		// c.catchMouse();

		Animal a = new Cat(); // 自动类型提升,猫对象提升了动物类型。但是特有功能无法s访问。
								// 作用就是限制对特有功能的访问。
								// 专业讲:向上转型。将子类型隐藏。就不用使用子类的特有方法。

		// a.eat();

		// 如果还想用具体动物猫的特有功能。
		// 你可以将该对象进行向下转型。
		// Cat c = (Cat)a;//向下转型的目的是为了使用子类中的特有方法。
		// c.eat();
		// c.catchMouse();

		// 注意:对于转型,自始自终都是子类对象在做着类型的变化。
		// Animal a1 = new Dog();
		// Cat c1 = (Cat)a1;//ClassCastException

		/*
		 * Cat c = new Cat();
		 * 
		 * // Dog d = new Dog();
		 * 
		 * // c.eat(); method(c); // method(d); // method(new Pig());
		 */

		method(new Dog());

	}

	public static void method(Animal a)// Animal a = new Dog();
	{
		a.eat();

		if (a instanceof Cat)// instanceof:用于判断对象的具体类型。只能用于引用数据类型判断
		// //通常在向下转型前用于健壮性的判断。

		{
			Cat c = (Cat) a;
			c.catchMouse();
		} else if (a instanceof Dog) {
			Dog d = (Dog) a;
			d.lookHome();
		} else {

		}

	}
	/*
	 * public static void method(Cat c) { c.eat(); } public static void
	 * method(Dog d) {
	 * }
	 */
}


示例(毕老师和毕姥爷的故事):

/*
 毕老师和毕姥爷的故事。
 */

class 毕姥爷 {
	void 讲课() {
		System.out.println("管理");
	}

	void 钓鱼() {
		System.out.println("钓鱼");
	}
}

class 毕老师 extends 毕姥爷 {
	void 讲课() {
		System.out.println("Java");
	}

	void 看电影() {
		System.out.println("看电影");
	}
}

class DuoTaiDemo2 {
	public static void main(String[] args) {
		// 毕老师 x = new 毕老师();
		// x.讲课();
		// x.看电影();

		毕姥爷 x = new 毕老师();
		x.讲课();
		x.钓鱼();

		毕老师 y = (毕老师) x;// ClassCastException
		y.看电影();

	}
}


多态下成员(成员变量、成员函数、静态成员函数)的特点:                         *一定要弄明白这个*

class Fu {
	int num = 3;
	void show() {
		System.out.println("fu show");
	}

	static void method() {
		System.out.println("fu static method");
	}
}

class Zi extends Fu {
	int num = 4;
	void show() {
		System.out.println("zi show");
	}

	static void method() {
		System.out.println("zi static method");
	}
}

class DuoTaiDemo3 {
	public static void main(String[] args) {
		Fu.method();
		Zi.method();
		Fu f = new Zi();//
		f.method();
		f.show();
		System.out.println(f.num);

		Zi z = new Zi();
		System.out.println(z.num);
	}
}


 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值