1、創建一個名稱為StaticDemo的類,並聲明一個靜態變量和一個普通變量。對變量分別賦予10和5的初始值。在main()方法中輸出變量值。
編寫代碼如下:
1 package org.hanqi.practise; 2 3 public class StaticDemo { 4 5 private static int i = 10; 6 private int j = 5; 7 public String a() 8 { 9 return "i="+i+" j="+j; 10 } 11 12 public static void main(String[] args) { 13 14 StaticDemo b = new StaticDemo(); 15 System.out.println(b.a()); 16 } 17 }
運行結果為:
2、建立一個汽車Auto類,包括輪胎個數,汽車顏色,車身重量、速度等成員變量。並通過不同的構造方法創建實例。至少要求: 汽車能夠加速,減速,停車。 再定義一個小汽車類Car,繼承Auto,並添加空調、CD等成員變量,覆蓋加速,減速的方法
編寫代碼如下:
創建Auto類:
1 package org.hanqi.practise; 2 3 public class Auto { 4 5 private int tyre; 6 private String color; 7 private double weight; 8 private double speed; 9 public Auto(int tyre, String color, double weight, double speed) { 10 super(); 11 this.tyre = tyre; 12 this.color = color; 13 this.weight = weight; 14 this.speed = speed; 15 } 16 public void accelerate() 17 { 18 System.out.println("Auto加速"); 19 } 20 public void deceleration() 21 { 22 System.out.println("Auto減速"); 23 } 24 public void stop() 25 { 26 System.out.println("Auto停車"); 27 } 28 }
創建Car類:
1 package org.hanqi.practise; 2 3 public class Car extends Auto { 4 5 6 public Car(int tyre, String color, double weight, double speed) { 7 super(tyre, color, weight, speed); 8 9 } 10 private String airconditioner; 11 private String CD; 12 public void accelerate() 13 { 14 System.out.println("Car加速"); 15 } 16 public void deceleration() 17 { 18 System.out.println("Car加速"); 19 } 20 }
3、創建一個名稱為Vehicle的接口,在接口中添加兩個帶有一個參數的方法start()和stop()。在兩個名稱分別為Bike和Bus的類中實現Vehicle接口。創建一個名稱為interfaceDemo的類,在interfaceDemo的main()方法中創建Bike和Bus對象,並訪問start()和stop()方法。
編寫代碼如下:
創建Vehicle接口:
1 package org.hanqi.practise; 2 3 public interface Vehicle { 4 5 public void start(); 6 public void stop(); 7 }
創建Bike類:
1 package org.hanqi.practise; 2 3 public class Bike implements Vehicle { 4 5 @Override 6 public void start() { 7 8 9 } 10 11 @Override 12 public void stop() { 13 14 15 } 16 }
創建Bus類:
1 package org.hanqi.practise; 2 3 public class Bus implements Vehicle { 4 5 @Override 6 public void start() { 7 8 } 9 10 @Override 11 public void stop() { 12 13 } 14 }
創建InterfaceDemo類:
1 package org.hanqi.practise; 2 3 public class InterfaceDemo { 4 5 public static void main(String[] args) { 6 7 Bike bike = new Bike(); 8 bike.start(); 9 bike.stop(); 10 System.out.println(); 11 Bus bus = new Bus(); 12 bus.start(); 13 bus.stop(); 14 } 15 }