您現在的位置是:首頁 > 動作武俠首頁動作武俠
面向物件的封裝、繼承和多型computer具有USB裝置的功能,USB介面
- 2023-01-17
解除封裝的裝備可以繼承嗎
一、實驗目的
1。掌握Java基本程式設計
2。掌握面向物件的封裝、繼承和多型的應用
二、實驗內容
電腦computer具有USB裝置的功能,預留USB介面,連結USB裝置
描述電腦類,USB介面,使用USB介面的滑鼠和鍵盤
n
USB介面,包含開啟裝置功能(open),和關閉裝置功能(close)
n
電腦類:屬性brand(品牌)開機功能(powerOn),輸出“XXX電腦正在啟動”關機功能(powerOff) ,輸出“XXX電腦在關閉”,使用裝置useDevice(USB usb)。
n
滑鼠類:實現USB介面,並具備點選方法(click)
n
鍵盤類:實現USB介面,並具備敲擊方法(type)
三、實驗過程(程式碼)
USB介面
public interface
USB
{
public void
open
();
public void
close
();
}
繼承介面的滑鼠類
public class
Mouse
implements
USB
{
public void
click
(){
System
。
out
。println(
“
單擊滑鼠
”
);
}
@Override
public void
open
() {
System
。
out
。println(
“
檢測滑鼠
”
);
}
@Override
public void
close
() {
System
。
out
。println(
“
關閉滑鼠
”
);
}
}
繼承介面的鍵盤類
public class
Keyboard
implements
USB
{
public void
type
(){
System
。
out
。println(
“
敲擊鍵盤
”
);
}
@Override
public void
open
() {
System
。
out
。println(
“
檢測鍵盤
”
);
}
@Override
public void
close
() {
System
。
out
。println(
“
關閉鍵盤
”
);
}
}
電腦類
public class
Computer
{
private
String
brand
;
public
Computer
(){
}
public
Computer
(
String
brand){
this
。
brand
= brand;
}
public
String
getBrand
(){
return this
。
brand
;
}
public void
setBrand
(
String
brand){
this
。
brand
= brand;
}
public void
powerOn
(){
System
。
out
。println(
brand
+
“
電腦正在啟動
”
);
}
public void
powerOff
(){
System
。
out
。println(
brand
+
“
電腦正在關閉
”
);
}
public void
useDevice
(
USB
usb){
usb。open();
if
(usb
instanceof
Mouse
){
Mouse m
= (
Mouse
)usb;
m
。click();
}
if
(usb
instanceof
Keyboard
){
((
Keyboard
) usb)。type();
//
匿名物件
}
usb。close();
}
}
測試類
public class
Test
{
public static void
main
(
String
[] args) {
Computer c
=
new
Computer(
“
聯想
”
);
c
。powerOn();
Mouse m
=
new
Mouse();
c
。useDevice(
m
);
Keyboard k
=
new
Keyboard();
c
。useDevice(
k
);
System
。
out
。println(
“
電腦品牌:
”
+
c
。getBrand());
c
。powerOff();
}
}