親プロセスパラメータとして形作ら1、
ステートメント:修飾型親クラスメソッド名(){}
図2に示すように、親クラスのメソッドは、値を返すように
ステートメント:修飾ボイド/戻り型メソッド名(親クラスタイプパラメータ名){}
コード例:
動物のカテゴリ:
/ * *
* @Author Mr.Wang
*ペットのクラス
*
* /
パブリック 抽象 クラス動物{
プライベート int型の健康; // 健康値
プライベート int型の愛; // 親密
プライベート文字列名; // 名前
パブリック int型getHealth(){
リターン健康;
}
公共 ボイド setHealth(INT 健康){
IF(健康< 0 ||健康> 100 ){
//;のSystem.out.println( "健全性値が0から100の間であるべきで、デフォルト値は60 Aである")
この .health = 60 ;
リターン;
}
この .health = 健康;
}
公共 のint getLove(){
戻り愛。
}
公共 ボイド setLove(INT 愛){
この .love = ラブ;
}
パブリック文字列のgetName(){
戻り名;
}
公共 ボイドのsetName(文字列名){
この .nameの= 名;
}
公共の動物(){}
公共の動物(int型健康、int型の愛、文字列名){
IF(健康< 0 ||健康> 100 ){
システム。OUT .println(「健康値は0〜100、デフォルト値の間でなければなりません60 Aである" ;)
この .health = 60 ;
} 他{
この .health = 健康;
}
この .love = 60 ;
この .nameの= 名;
}
// ペットの告白
公共 ボイド印刷(){
システム。OUT .println(" ペット告白:" );
システム。OUTの .printlnは(" 私の名前は" + この .getName()+ " 値が健康である" + この .getHealth( )+ " の最初の親密" + この.getLove());
}
公共 ボイドプレイ(){
};
公共 ボイドバース(){
。システムOUT .println(" マスターはです" +この .getName()+ " バス" );
}
}
ペンギンカテゴリ:
/**
* @author Mr.Wang
* 企鹅类
*
*/
public class Penguin extends Animals{
private String sex;
public Penguin() {}
public Penguin(int health, int love, String name,String sex) {
super(health, love, name);
this.sex = sex;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public void print() {
super.print();
System.out.println("我是一只"+this.sex+this.getName());
}
public void play() {
System.out.println("主人在跟"+this.getName()+"玩水");
}
}
狗狗类:
/**
* @author Mr.Wang
* 狗狗类
*
*/
public class Dog extends Animals{
private String type;
public Dog() {}
public Dog(int health, int love, String name,String type) {
super(health, love, name);
this.type = type;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public void print() {
super.print();
System.out.println("我是一只"+this.type);
}
public void play() {
System.out.println("主人正在跟"+this.getName()+"玩飞盘");
}
}
主人类:
public class Master {
public Animals toPlay(int num) {
if(num == 1) {
return new Dog(90,90,"皮蛋","拉布拉多");
}else {
return new Penguin(90,90,"小胡","Q仔");
}
}
public void toBath(Animals animals) {
animals.Bath();
}
}
测试类:
public class Text03 {
public static void main(String[] args) {
Master master = new Master();
Animals animals = master.toPlay(1);
animals.play();
master.toBath(animals);
}
}
测试运行结果: