面向对象的特性的应用:多态

代码如下:

package four.day8.com;

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("人吃饭");
}
}

 

 

package four.day8.com;

public class Women extends Person {
private boolean isbeauty;

public boolean isIsbeauty() {
return isbeauty;
}

public void setIsbeauty(boolean isbeauty) {
this.isbeauty = isbeauty;
}

public Women() {
super();
}

public Women(boolean isbeauty) {
super();
this.isbeauty = isbeauty;
}
public void walk(){
System.out.println("女人:窈窕淑女,君子好逑!!!!!!");
}
public void eat(){
System.out.println("女人:要少吃点,减肥!!!!!");
}
public void shopping(){
System.out.println("女人:爱购物");
}


}

 

 

package four.day8.com;

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 enterTramint(){
System.out.println("男人好客之道:请客");
}

}

 

package four.day8.com;


/**
* 面向对象的特征性:多态性
* 1,多态性指的是什么?多态性,可以理解为一个事物的动作表现形态
* 1)方法的重载与重写 2)子类的多态性
* **/
public class TestPerson {

public static void main(String[] args) {
Person pp = new Person();
pp.eat();
pp.walk();
Man man = new Man();
man.walk();
man.eat();

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

if(p1 instanceof Women){
Women www = new Women();
www.shopping();
}
if(p1 instanceof Man){
Man mm = new Man();
mm.enterTramint();
}

}

}

 

posted @ 2016-08-08 15:35  caocx  阅读(270)  评论(0编辑  收藏  举报