您当前的位置:首页 > 百宝箱

java接口编程题

2024-09-30 21:06:04 作者:石家庄人才网

本篇文章给大家带来《java接口编程题》,石家庄人才网对文章内容进行了深度展开说明,希望对各位有所帮助,记得收藏本站。

1. 设计一个动物接口Animal,包含吃(eat)和睡觉(sleep)两个方法,然后定义猫(Cat)和狗(Dog)类实现Animal接口,并实现接口中的方法。

```javainterface Animal { void eat(); void sleep();}class Cat implements Animal { @Override public void eat() { System.out.println("猫吃鱼..."); } @Override public void sleep() { System.out.println("猫在睡觉..."); }}class Dog implements Animal { @Override public void eat() { System.out.println("狗吃骨头..."); } @Override public void sleep() { System.out.println("狗在睡觉..."); }}public class Example1 { public static void main(String[] args) { Cat cat = new Cat(); cat.eat(); cat.sleep(); Dog dog = new Dog(); dog.eat(); dog.sleep(); }}```

2. 设计一个图形接口Shape,包含计算面积(calculateArea)和计算周长(calculatePerimeter)两个方法,然后定义圆形(Circle)和矩形(Rectangle)类实现Shape接口,并实现接口中的方法。

```javainterface Shape { double calculateArea(); double calculatePerimeter();}class Circle implements Shape { private double radius; public Circle(double radius) { this.radius = radius; } @Override public double calculateArea() { return Math.PI * radius * radius; } @Override public double calculatePerimeter() { return 2 * Math.PI * radius; }}class Rectangle implements Shape { private double length; private double width; public Rectangle(double length, double width) { this.length = length; this.width = width; } @Override public double calculateArea() { return length * width; } @Override public double calculatePerimeter() { return 2 * (length + width); }}public class Example2 { public static void main(String[] args) { Circle circle = new Circle(5); System.out.println("圆形的面积:" + circle.calculateArea()); System.out.println("圆形的周长:" + circle.calculatePerimeter()); Rectangle rectangle = new Rectangle(4, 6); System.out.println("矩形的面积:" + rectangle.calculateArea()); System.out.println("矩形的周长:" + rectangle.calculatePerimeter()); }}```

3. 定义一个USB接口,包含连接(connect)和断开连接(disconnect)两个方法,然后定义鼠标(Mouse)和键盘(Keyboard)类实现USB接口,并实现接口中的方法。

```javainterface USB { void connect(); void disconnect();}class Mouse implements USB { @Override public void connect() { System.out.println("鼠标已连接"); } @Override public void disconnect() { System.out.println("鼠标已断开连接"); }}class Keyboard implements USB { @Override public void connect() { System.out.println("键盘已连接"); } @Override public void disconnect() { System.out.println("键盘已断开连接"); }}public class Example3 { public static void main(String[] args) { Mouse mouse = new Mouse(); mouse.connect(); mouse.disconnect(); Keyboard keyboard = new Keyboard(); keyboard.connect(); keyboard.disconnect(); }}```

版权声明:《java接口编程题》来自【石家庄人才网】收集整理于网络,不代表本站立场,所有图片文章版权属于原作者,如有侵略,联系删除。
https://www.ymil.cn/baibaoxiang/1530.html