首先创建父类,因为BYD和BMW同输入汽车,有共同的属性和方法
1 public class Car {
2 int price;
3 String type;
4 String color;
5 public Car() {
6 super();
7 }
8 public Car(int price, String type, String color) {
9 super();
10 this.price = price;
11 this.type = type;
12 this.color = color;
13 }
14
15 public void show(){
16 System.out.println("I can run!");
17 }
18 }
创建BYD子类,并重写方法
1 public class BYD extends Car {
2
3 public BYD() {
4 super();
5 }
6
7 public BYD(int price, String type, String color) {
8 super(price, type, color);
9 }
10
11 public void show(){
12 System.out.println("BYD");
13 System.out.println("价格"+price);
14 System.out.println("型号"+type);
15 System.out.println("颜色"+color);
16 }
17 }
1 public class BMW extends Car {
2
3 public BMW() {
4 super();
5 }
6
7 public BMW(int price, String type, String color) {
8 super(price, type, color);
9 }
10
11 public void show(){
12 System.out.println("BMW");
13 System.out.println("价格"+price);
14 System.out.println("型号"+type);
15 System.out.println("颜色"+color);
16 }
17 }
静态和非静态的问题也要注意,到底是谁调用
1 public class Driver {
2 static String name;
3
4 public Driver(String sex) {
5 this.name = name;
6 }
7 public Driver() {
8 }
9 /*
10 * 创建方法
11 */
12 public static void drive(Car A){//static?
13 System.out.println(name+"Let's run!");
14 A.show();
15 }
16
17 public static void main(String[] args) {
18 Driver driver=new Driver("张三");
19 Car byd=new BYD(3000000,"唐","红");
20 driver.drive(byd);//这样调用可以不是static
21 Car bmw=new BMW(8000000,"x5","黑");
22 Driver.drive(bmw);//这样调用必须是static
23 }
24 }