本文章是我个人对JAVA基础概念的一个复习的练习代码,里面涉及了面对对象编程:多态,抽象类,静态类/变量,接口。还有错误处理的技术。
1.为主函数
package test_duotai; public class test3 { public static void main(String [] args) { Panzer4 d = new Panzer4(25,75,"d",40);//声明类 System.out.println(d.getType()); d.move_1(); Panzer4.tank_fire();//因为这个方法是静态的,所以要这样调用 Panzer4 d1 = new Panzer4(25,75,"d",40); Panzer4.asd += 1;//asd是一个未被封装的静态变量 d1.engine(); try //异常处理,除非值是20都会被catch { d.enter_num(21); } catch(try_catch_tank e) { System.out.println("you have to enter 20 to avoid this error ." + e.get_error(21)); e.printStackTrace(); } } }
2.抽象类Tank,被Panzer4继承
package test_duotai; public abstract class Tank { private int ammo; private int armor; private String type; public Tank(int ammo,int armor,String type) { System.out.println("Constructing an Tank"); this.ammo = ammo; this.armor = armor; this.type = type; } public String getType() { return type; } public int getammo() { return ammo; } public void setammo(int ammo_in) { ammo = ammo_in; } public int getarmor() { return armor; } public abstract void move_1();//抽象方法,由子类定义 public static void tank_fire() //静态方法 { System.out.println("Boom!"); } }
3.接口
package test_duotai; public interface moblie { //接口要求Panzer4定义两个类 public void engine(); public void gas(); }
4.子类,继承了Tank,调用了moblie接口。
package test_duotai; public class Panzer4 extends Tank implements moblie { private int supercharge; public static int asd = 30;//静态变量,供所有的panzer4实例使用。 public Panzer4(int ammo,int armor,String type,int supercharge) { super(ammo,armor,type); set_super(supercharge); } public void set_super(int supercharge_in) { supercharge = supercharge_in; } public void move_1() { System.out.println("Panzer 4 on the move"); } public void use_super() { System.out.println("fire supercharge : " + supercharge); } public void engine() { System.out.println("fire engine"); } public void gas() { System.out.println("gas"); } public int enter_num(int test_num) throws try_catch_tank { if (test_num == 20) { } else { throw new try_catch_tank(test_num); } return test_num; } }
5.异常处理
package test_duotai; public class try_catch_tank extends Exception { int test_num; public try_catch_tank(int test_num) { this.test_num = test_num; } public int get_error(int test_num) { return test_num; } }