返学费网 > 培训机构 > 南宁达内教育

13277840061

全国统一学习专线 8:30-21:00

南宁达内:Java类继承以及接口实现实例


  Java类继承以及接口实现实例:这个实例非常容易理解,贴在这里与大家共享。

  1 //抽象父类,交通工具(Vehicle) 2 public abstract class Vehicle{ 3

  private String name; 4

  private double cost; 5

  6

  //无参构造函数

  7

  public Vehicle(){ 8

  } 9 10

  //有参构造函数 11

  public Vehicle(String name, double cost){ 12

  this.name = name; 13

  this.cost = cost; 14

  } 15 16

  //父类的抽象方法,在子类中要具体实现。

  17

  public abstract void run();

  18

  public abstract void stop(); 19 20

  //getter方法

  21

  public String getName(){ 22

  return this.name; 23

  } 24 25

  public double getCost(){ 26

  return this.cost; 27

  } 28 29

  //setter方法 30

  public void setName(String name){ 31

  this.name = name; 32

  } 33 34

  public void setCost (double cost){ 35

  this.cost = cost; 36

  }

  37 } 38 39 40 41 //上缴养路费的接口 42 public interface interRoadTax{ 43

  public void tax(); 44 } 45 46 47 48 //子类自行车Bike,继承Vehicle 49 public class Bike extends Vehicle{ 50

  private int bikeType; 51 52

  //无参构造函数 53

  public Bike(){} 54

  55

  //有参构造函数 56

  public Bike(String name, double cost, int type){ 57

  super(name,cost); //通过父类方法进行赋值 58

  this.bikeType = type; 59

  } 60 61

  //setter方法

  62

  public void setBikeType(int type){ 63

  this.bikeType = type; 64

  } 65

  66

  //getter方法 67

  public int getBikeType(){ 68

  return this.bikeType; 69

  } 70

  71

  //继承父类Vehicle的抽象方法,在子类中要具体实现。 72

  public void run(){ 73

  System.out.println("i am bike and running……"); 74

  } 75 76

  //继承父类Vehicle的抽象方法,在子类中要具体实现。

  77

  public void stop(){ 78

  System.out.println("i am bike and stopping……"); 79

  } 80 } 81 82 83 84 //子类汽车Car,继承Vehicle,同时实现interRoadTax接口 85 public class Car extends Vehicle implements interRoadTax{ 86

  private int numberOfPeople; 87

  88

  //无参构造函数 89

  public Car(){} 90

  91

  //有参构造函数 92

  public Car(String name, double cost, int numberOfPeople){ 93

  super(name,cost);//通过父类方法进行赋值 94

  this.numberOfPeople = numberOfPeople; 95

  } 96

  97

  //getter方法 98

  public int getNumberOfPeople(){ 99

  return this.numberOfPeople;100

  }101

  102

  public void setNumberOfPeople(int numberOfPeople){103

  this.numberOfPeople = numberOfPeople;104

  }105

  106

  //继承父类Vehicle的抽象方法,在子类中要具体实现。107

  public void run(){108

  System.out.println("i am car and running……");109

  }110 111

  //继承父类Vehicle的抽象方法,在子类中要具体实现。112 public void stop(){113

  System.out.println("i am car and stopping……");114

  }115 116

  //实现上缴养路费的接口方法

  117

  public void tax(){118

  System.out.println("the car tax is " + getCost() * 0.1);119

  }

  120 }121 122 123 124 //子类摩托车Motor,继承Vehicle,同时实现interRoadTax接口125 public class Motor extends Vehicle implements interRoadTax{126

  public Motor(){}127

  public Motor(String name,double cost){128

  super(name,cost);129

  }130

  131

温馨提示:为不影响您的学业,来校区前请先电话咨询,方便我校安排相关的专业老师为您解答

  • 详情请进入南宁达内教育
  • 已关注:186
  • 咨询电话:
姓名不能为空
手机号格式错误