父类
1 package hello; 2 3 public class Yinshuiji {//创建父类饮水机 4 5 6 public Yinshuiji(String pinpai,int shuiliang){//构造方法 7 8 this.pinpai = pinpai;//品牌 9 this.shuiliang = shuiliang;//当前水量 10 System.out.println("饮水机品牌是:" +pinpai + ", 当前水量为" +shuiliang ); 11 12 } 13 14 String pinpai; 15 int shuiliang; 16 int shengyushuiliang; 17 18 //方法一:接水 19 public void jieshui(int jieshuiliang){ 20 21 if(jieshuiliang > shuiliang){ 22 System.out.println("已经没水了"); 23 } 24 else 25 { 26 shengyushuiliang = shuiliang - jieshuiliang; 27 System.out.println("饮水机剩余水量 = " + shengyushuiliang); 28 } 29 30 } 31 32 //方法二:烧水 33 public void shaoshui(int time){ 34 35 int shuiwen = 20; 36 shuiwen = shuiwen + time * 10; 37 if(shuiwen > 100) 38 { 39 System.out.println("水已经开了"); 40 } 41 else 42 { 43 System.out.println("现在水温 = " + shuiwen); 44 } 45 46 } 47 48 49 }
子类
package hello; public class Dagonglvysj extends Yinshuiji {//创建子类大功率饮水机 public Dagonglvysj(String pinpai, int shuiliang) { super(pinpai, shuiliang); // TODO Auto-generated constructor stub } //重写父类方法二 public void shaoshui(int time) { int shuiwen = 20; shuiwen = shuiwen + time * 20; if(shuiwen > 100) { System.out.println("水已经开了"); } else { System.out.println("现在水温 = " + shuiwen); } } }
向上转型
package hello; public class Test { public static void main(String[] args){ Yinshuiji ysj = new Dagonglvysj("美帝",50);//向上转型 ysj.shaoshui(2);//调用子类重写的方法二