第一题
定义一个抽象类为形状类Shape,其中包含抽象方法display(),在其子类圆形Circle和长方形Rectangle中实现该抽象方法,分别输出“这是一个圆形”和“这是一个长方形”。编写MainClass,在其main()函数中进行测试。
代码块
abstract class Shape {
abstract void display();
}
class Circle extends Shape{
void display(){
System.out.println("这是一个圆形");
}
}
class Rectangle extends Shape{
void display(){
System.out.println("这是一个长方形");
}
}
public class MainClass {
public static void main(String[] args) {
// TODO Auto-generated method stub
Shape circle =new Circle();
Shape rectangle =new Rectangle();
circle.display();
rectangle.display();
}
}
第二题
万能接口USB
定义一个接口Usb,其中包含一个workInConnection()方法。定义鼠标类(Mouse)和手机类(MobilePhone),分别实现该接口,再编写一个测试类(TestInterface)创建鼠标和手机对象并调用workInConnection()方法。
代码块
interface Usb {
void workInConnection();
}
class Mouse implements Usb{
public void workInConnection() {
System.out.println("鼠标连接成功");
}
}
class MobilePhone implements Usb{
public void workInConnection() {
System.out.println("手机连接成功");
}
}
public class TestInterface {
public static void main(String[] args) {
// TODO Auto-generated method stub
Usb mouse = new Mouse();
Usb mobilePhone = new MobilePhone();
mouse.workInConnection();
mobilePhone.workInConnection();
}
}
第三题
天气预报
天气可能出现不同的状态,要求用接口封装天气的状态。具体要求如下:
(1)编写一个接口WeatherState,该接口有一个名为void showState()的方法。
(2)编写Weather类,该类中有一个接口WeatherState接口声明的变量state。另外,该类有一个show()方法,在该方法中让接口state回调showState()方法。
(3)编写若干上实现WeatherState接口的类,负责刻画天气的各种状态。
public interface WeatherState { //接口
public void showState();
}
public class Weather {
WeatherState state;
public void show() {
state.showState();
}
public void setState(WeatherState s) {
state = s;
}
}
public class WeatherForecast { //主类
public static void main(String args[]) {
Weather weatherBeijing =new Weather();
System.out.print("\n今天白天:");
weatherBeijing.setState(new CloudyDayState());
weatherBeijing.show();
System.out.print("\n今天夜间:");
weatherBeijing.setState(new LightRainState());
weatherBeijing.show();
System.out.print("转:");
weatherBeijing.setState(new HeavyRainState());
weatherBeijing.show();
System.out.print("\n明天白天:");
weatherBeijing.setState(new LightRainState());
weatherBeijing.show();
System.out.print("\n明天夜间:");
weatherBeijing.setState(new CloudyLittleState());
weatherBeijing.show();
}
}
public class CloudyLittleState implements WeatherState {
public void showState() {
System.out.print("少云,有时晴.");
}
}
public class CloudyDayState implements WeatherState {
public void showState() { //重写public void showState()
System.out.print("多云.");
}
}
public class HeavyRainState implements WeatherState{
public void showState() { //重写public void showState()
System.out.print("大雨.");
}
}
public class LightRainState implements WeatherState {
public void showState() {//重写public void showState()方法
System.out.print("小雨.");
}}
生命可以随心所欲,但不能随波逐流。