1.创建一个图书类(Book), 并在该类中定义3个成员变量图书编号(id)、 图书名称 (name)以及作者(author), 再定义-一个方法(setBook) 为这3个成员赋值。在main()方法中,词用setBook方法,并将图书编号和图书名称输出。 2使用单例模式实现仅能创建Book类的3个实例。 3.使用方法的重载方式实现计算矩形面积和圆面积的方法。
时间: 2024-02-06 19:10:51 浏览: 112
VC中类的定义及其案例共3页.pdf.zip
1. 代码如下:
```java
public class Book {
private int id;
private String name;
private String author;
public void setBook(int id, String name, String author) {
this.id = id;
this.name = name;
this.author = author;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getAuthor() {
return author;
}
public static void main(String[] args) {
Book book = new Book();
book.setBook(123, "Java基础教程", "张三");
System.out.println("图书编号:" + book.getId() + ",图书名称:" + book.getName());
}
}
```
2. 单例模式实现代码如下:
```java
public class Book {
private int id;
private String name;
private String author;
private static Book instance1 = new Book();
private static Book instance2 = new Book();
private static Book instance3 = new Book();
private Book() {}
public static Book getInstance(int index) {
switch (index) {
case 1:
return instance1;
case 2:
return instance2;
case 3:
return instance3;
default:
return null;
}
}
public void setBook(int id, String name, String author) {
this.id = id;
this.name = name;
this.author = author;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getAuthor() {
return author;
}
public static void main(String[] args) {
Book book1 = Book.getInstance(1);
book1.setBook(123, "Java基础教程", "张三");
System.out.println("图书编号:" + book1.getId() + ",图书名称:" + book1.getName());
Book book2 = Book.getInstance(2);
book2.setBook(456, "Python基础教程", "李四");
System.out.println("图书编号:" + book2.getId() + ",图书名称:" + book2.getName());
Book book3 = Book.getInstance(3);
book3.setBook(789, "C#基础教程", "王五");
System.out.println("图书编号:" + book3.getId() + ",图书名称:" + book3.getName());
}
}
```
3. 计算矩形面积和圆面积的方法重载代码如下:
```java
public class CalculateArea {
public static double getArea(double width, double height) {
return width * height;
}
public static double getArea(double radius) {
return Math.PI * radius * radius;
}
public static void main(String[] args) {
double width = 3.5;
double height = 5.2;
double radius = 2.0;
double rectangleArea = getArea(width, height);
System.out.println("矩形面积:" + rectangleArea);
double circleArea = getArea(radius);
System.out.println("圆面积:" + circleArea);
}
}
```
阅读全文