Java继承_接口练习题

时间:2020-12-27 17:01:24

1、创建一个名称为StaticDemo的类,并声明一个静态变量和一个普通变量。对变量分别赋予10和5的初始值。在main()方法中输出变量值。

编写代码如下:

 package org.hanqi.practise;

 public class StaticDemo {

      private static int i = 10;
private int j = 5;
public String a()
{
return "i="+i+" j="+j;
} public static void main(String[] args) { StaticDemo b = new StaticDemo();
System.out.println(b.a());
}
}

运行结果为:

Java继承_接口练习题

2、建立一个汽车Auto类,包括轮胎个数,汽车颜色,车身重量、速度等成员变量。并通过不同的构造方法创建实例。至少要求:  汽车能够加速,减速,停车。 再定义一个小汽车类Car,继承Auto,并添加空调、CD等成员变量,覆盖加速,减速的方法

编写代码如下:

创建Auto类:

 package org.hanqi.practise;

 public class Auto {

     private int tyre;
private String color;
private double weight;
private double speed;
public Auto(int tyre, String color, double weight, double speed) {
super();
this.tyre = tyre;
this.color = color;
this.weight = weight;
this.speed = speed;
}
public void accelerate()
{
System.out.println("Auto加速");
}
public void deceleration()
{
System.out.println("Auto减速");
}
public void stop()
{
System.out.println("Auto停车");
}
}

创建Car类:

 package org.hanqi.practise;

 public class Car extends Auto {

     public Car(int tyre, String color, double weight, double speed) {
super(tyre, color, weight, speed); }
private String airconditioner;
private String CD;
public void accelerate()
{
System.out.println("Car加速");
}
public void deceleration()
{
System.out.println("Car加速");
}
}

3、创建一个名称为Vehicle的接口,在接口中添加两个带有一个参数的方法start()和stop()。在两个名称分别为Bike和Bus的类中实现Vehicle接口。创建一个名称为interfaceDemo的类,在interfaceDemo的main()方法中创建Bike和Bus对象,并访问start()和stop()方法。

编写代码如下:

创建Vehicle接口:

 package org.hanqi.practise;

 public interface Vehicle {

     public void start();
public void stop();
}

创建Bike类:

 package org.hanqi.practise;

 public class Bike implements Vehicle {

     @Override
public void start() { } @Override
public void stop() { }
}

创建Bus类:

 package org.hanqi.practise;

 public class Bus implements Vehicle {

     @Override
public void start() { } @Override
public void stop() { }
}

创建InterfaceDemo类:

 package org.hanqi.practise;

 public class InterfaceDemo {

     public static void main(String[] args) {

         Bike bike = new Bike();
bike.start();
bike.stop();
System.out.println();
Bus bus = new Bus();
bus.start();
bus.stop();
}
}