多态性简单实例

1.首先建立一个父类Person:

package com.atguigu.java_duotai;

public class Person {
	private String name;
	private int age;

	public Person() {
		super();
	}

	public Person(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public void walk() {
		System.out.println("人走路");
	}

	public void eat() {
		System.out.println("人吃饭");
	}

}

 

2.再建立一个子类Man

package com.atguigu.java_duotai;

public class Man extends Person {
	private boolean smoking;

	public Man() {
		super();
	}

	public Man(boolean smoking) {
		super();
		this.smoking = smoking;
	}

	public boolean isSmoking() {
		return smoking;
	}

	public void setSmoking(boolean smoking) {
		this.smoking = smoking;
	}
	
	public void walk() {
		System.out.println("男人走路");
	}

	public void eat() {
		System.out.println("男人吃饭");
	}
	
	public void entertainment(){
		System.out.println("男人请客");
	}
}

 

3.再建一个子类Woman:

package com.atguigu.java_duotai;

public class Woman extends Person {
	private boolean isBeauty;

	public Woman() {
		super();
	}

	public Woman(boolean isBeauty) {
		super();
		this.isBeauty = isBeauty;
	}

	public boolean isBeauty() {
		return isBeauty;
	}

	public void setBeauty(boolean isBeauty) {
		this.isBeauty = isBeauty;
	}

	public void walk() {
		System.out.println("女人走路");
	}

	public void eat() {
		System.out.println("女人吃饭");
	}
	
	public void shopping(){
		System.out.println("女人购物");
	}

}

 

4.新建一个测试类TestPerson:

package com.atguigu.java_duotai;

/*
 * 特征三:多态性
 * 1.可以理解为一个事物的多种表现形式
 *   >方法的重载与重写
 *   >子类对象的多态性
 * 
 * 2.子类对象的多态性使用的前提:
 * 	 >要有类的继承
 *   >要有子类对父类方法的重写
 * 
 * 3.程序运行分为编译状态和运行状态
 *   对于多态性来说,编译时,“看左边”,将此引用变量理解为父类的类型
 *   运行时,“看右边”,关注真正对象的实体:子类的对象。那么执行的方法就是子类重写的。
 *
 * 4.属性不具有多态性(重名的话只看"左边")
 */
public class TestPerson {
	public static void main(String[] args) {
		Person p = new Person();
		p.eat();
		p.walk();

		Man m = new Man();
		m.eat();
		m.walk();
		m.entertainment();

		// 子类对象的多态性:父类的引用指向子类对象
		Person p1 = new Man();// 向上转型
		// 虚拟方法调用:通过父类的引用指向子类的对象实体,当调用方法时实际执行的是子类重写父类的
		p1.eat();
		p1.walk();
		// p1.entertainment();

		Person p2 = new Woman();
		p2.eat();
		p2.walk();
		// p2.shopping();
		Woman w = (Woman) p2;// 向下转型,使用强转符()
		w.shopping();

		// 编译时没错,运行时java.lang.ClassCastException
		// Woman w1 = (Woman)p1;
		// w1.shopping();

		// instanceof:
		// 格式:对象a instanceof 类A :判断对象a是否是类A的实例
		// 是的话返回true否false,是的话也一定是A类的父类的实例
		if (p1 instanceof Woman) {
			System.out.println("dddddd");
			Woman w1 = (Woman) p1;
			w1.shopping();
		}
		if (p1 instanceof Man) {
			System.out.println("ffffff");
			Man m1 = (Man) p1;
			m1.entertainment();
		}
		if (p1 instanceof Person) {
			System.out.println("hhhhhhh");
		}
	}
}

 

5.运行结果:

男人吃饭
男人走路
女人吃饭
女人走路
女人购物
ffffff
男人请客
hhhhhhh

 

猜你喜欢

转载自jsbylibo.iteye.com/blog/2162816
今日推荐