Java多态
package Li;
public abstract class Human {
private String name;
private int love;
private int health;
public Human ( ) {
}
public Human ( String name) {
this . name= name;
}
public String getName ( ) {
return name;
}
public void setName ( String name) {
this . name = name;
}
public int getLove ( ) {
return love;
}
public void setLove ( int love) {
this . love = love;
}
public int getHealth ( ) {
return health;
}
public void setHealth ( int health) {
this . health = health;
}
public abstract void eat ( ) ;
}
package Li;
public class Son extends Human {
public void eat ( ) {
if ( this . getHealth ( ) == 100 ) {
System. out. println ( "儿子吃饱了" + this . getHealth ( ) ) ;
} else {
this . setHealth ( this . getHealth ( ) + 10 ) ;
System. out. print ( "儿子健康值:" + this . getHealth ( ) ) ;
}
}
public void football ( ) {
this . setHealth ( getHealth ( ) - 20 ) ;
this . setLove ( getLove ( ) + 15 ) ;
System. out. print ( "儿子玩足球游戏" ) ;
}
}
package Li;
public class Daughter extends Human {
public void eat ( ) {
if ( this . getHealth ( ) == 100 ) {
System. out. println ( "女儿吃饱了" + this . getHealth ( ) ) ;
} else {
this . setHealth ( this . getHealth ( ) + 10 ) ;
System. out. print ( "女儿健康值:" + this . getHealth ( ) ) ;
}
}
public void skip ( ) {
this . setHealth ( this . getHealth ( ) - 3 ) ;
this . setLove ( this . getLove ( ) + 10 ) ;
System. out. print ( "女儿玩跳绳游戏" ) ;
}
}
package Li;
public class Father {
public void feed ( Son son) {
son. eat ( ) ;
System. out. println ( "父亲喂饭给儿子吃" ) ;
}
public void feed ( Daughter daughter) {
daughter. eat ( ) ;
System. out. println ( "父亲喂饭给女儿吃" ) ;
}
public void feed ( Human human) {
human. eat ( ) ;
}
public void play ( Human human) {
if ( human instanceof Son ) {
Son son= ( Son) human;
son. football ( ) ;
} else if ( human instanceof Daughter ) {
Daughter daughter= ( Daughter) human;
daughter. skip ( ) ;
}
}
}
package Li;
public class Test {
public static void main ( String[ ] args) {
Father father= new Father ( ) ;
Son son= new Son ( ) ;
son. setHealth ( 100 ) ;
father. feed ( son) ;
Daughter daughter= new Daughter ( ) ;
daughter. setHealth ( 40 ) ;
father. feed ( daughter) ;
Human human= new Son ( ) ;
human. setHealth ( 60 ) ;
father. feed ( human) ;
Human human2= new Daughter ( ) ;
human. setHealth ( 82 ) ;
father. feed ( human2) ;
}
}
package Li;
public class Test2 {
public static void main ( String[ ] args) {
Father father= new Father ( ) ;
Human human= new Son ( ) ;
father. play ( human) ;
}
}