父类作为方法的形参以及父类作为方法返回值
生活随笔
收集整理的這篇文章主要介紹了
父类作为方法的形参以及父类作为方法返回值
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1、父類作為方法的形參
語句:修飾符 父類類型 方法名(){}
2、父類作為方法返回值
語句:修飾符 void/返回值類型 方法名(父類類型 形參名){}
代碼例子:
動物類:
/*** @author Mr.Wang* 寵物類**/ public abstract class Animals {private int health;//健康值private int love;//親密度private String name;//名字public int getHealth() {return health;}public void setHealth(int health) {if(health<0||health>100){//System.out.println("健康值應該在0至100之間,默認值為60。");this.health=60;return;}this.health = health;}public int getLove() {return love;}public void setLove(int love) {this.love = love;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Animals() {}public Animals(int health, int love, String name) {if(health<0||health>100){System.out.println("健康值應該在0至100之間,默認值為60。");this.health=60;}else {this.health = health;}this.love = 60;this.name = name;}//寵物自白public void print() {System.out.println("寵物的自白:");System.out.println("我的名字叫"+this.getName()+",健康值是"+this.getHealth()+",初始親密度為"+this.getLove());}public void play() {};public void Bath() {System.out.println("主人正在給"+this.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);} }測試運行結果:
?
轉載于:https://www.cnblogs.com/Dean-0/p/11203434.html
總結
以上是生活随笔為你收集整理的父类作为方法的形参以及父类作为方法返回值的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: BZOJ1706奶牛接力跑
- 下一篇: 在Atlas服务器端实现中推荐使用Web