java中怎么具体使用抽象类和接口???
发布网友
发布时间:2022-04-21 07:24
我来回答
共3个回答
热心网友
时间:2022-06-18 16:53
//继承抽象类Car并实现接口Gasoline
class MyCar extends Car implements Gasoline{
//定义一个变量模拟当前档位,如1,2,3,4,5,
public int nowShift;
//无参构造方法,默认设置相关属性
public MyCar(){
this.color=Color.red;
this.gearNum=5;
this.tiretype="BridgeStone185ST";
this.engine=(float)1598.5;
}
//自己创建车时指定相关属性
public MyCar(Color c,int gearNum,String tiretype,float engine){
this.gearNum=gearNum;
this.color=c;
this.tiretype=tiretype;
this.engine=engine;
}
public void shiftgear(){
//简单模拟循环档,每次调用时档位加1,加满后归零
nowShift++;
if(nowShift>=5)
nowShift=0;
}
public void brake(){
nowShift=0;
System.out.println("正在刹车...");
}
public void aircon(){
System.out.println("冷气已经打开");
}
public void headlight(){
System.out.println("大灯打开...");
}
public void refuel(){
System.out.println("轿车燃料为:"+FUEL);
}
public void equipment(){
System.out.println("轿车颜色:"+color+" "+"排挡数:"+gearNum+"\n"+"轮胎型号:"+tiretype+" "+"尾气排量:"+engine+" "+"轿车燃料:"+FUEL);
}
public static void main(String[]a){
new MyCar().equipment();
}
}
main()方法里只测试了自定义的equitment()方法,其他的和他一样调用,如果你需要的话、希望对你有帮助
热心网友
时间:2022-06-18 16:54
public class MyCar extends Car implements Gasoline{
@Override
public void aircon() {
System.out.println("冷气开放");
}
@Override
public void brake() {
System.out.println("刹车!");
}
@Override
public void headlight() {
System.out.println("开启大灯!");
}
@Override
public void shiftgear() {
System.out.println("换档!!");
}
@Override
public void refuel() {
System.out.println("执行refuel方法!");
}
public void equipment(){
System.out.println("颜色="+this.color+ " 排挡数="+this.gearNum+" 轮胎型号="+this.tiretype+" 排气量="+this.engine+" 燃料="+this.FUEL);
}
public static void main(String args[]){
MyCar myCar = new MyCar();
myCar.color=new Color(255,0,0);
myCar.gearNum=5;
myCar.tiretype="BridgeStone185ST";
myCar.engine=1598.5f;
myCar.aircon();
myCar.shiftgear();
myCar.brake();
myCar.headlight();
myCar.equipment();
}
}
热心网友
时间:2022-06-18 16:54
自己的类mycar要继承抽象类Car,用extends,实现Gasoline接口用implements,如下:
public mycar extends Car implements Gasoline()
在你的类里面实现其中的抽象方法即可。