添加参考答案

This commit is contained in:
OrangeCat 2021-07-28 13:22:22 +08:00 committed by GitHub
parent a07a12fbe8
commit 59bc12c3f7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 123 additions and 0 deletions

View File

@ -46,10 +46,133 @@ public class GoShopping {
#### 练习1
创建 Shape图形该类中有一个计算面积的方法。圆形和矩形都继承自图形类输出圆形和矩形的面积。
```java
public class Circle extends Shape {
double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double getArea() {
return Math.PI * this.radius * this.radius;
}
}
public class Rectangle extends Shape {
double length;
double width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
@Override
public double getArea() {
return this.length * this.width;
}
}
public abstract class Shape {
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public abstract double getArea();
}
public class Test {
public static void main(String[] args) {
Circle circle = new Circle(1.5);
circle.name = "圆形";
System.out.println(circle.name + "面积:" + circle.getArea());
Rectangle rectangle = new Rectangle(5.5, 2);
rectangle.name = "矩形";
System.out.println(rectangle.name + "面积:" + rectangle.getArea());
}
}
```
#### 练习2
创建工厂类,工厂类中有一个抽象的生产方法,创建汽车厂和鞋厂类,重写工厂类中的抽象生产方法,输出汽车厂生产的是汽车,鞋厂生产的是鞋。
```java
public class AutoPlant extends Factory {
String productsName;
public AutoPlant(String productsName) {
this.productsName = productsName;
}
@Override
public String produce() {
return this.productsName;
}
}
public abstract class Factory {
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public abstract String produce();
}
public class ShoeFactory extends Factory {
String productsName;
public ShoeFactory(String productsName) {
this.productsName = productsName;
}
@Override
public String produce() {
return this.productsName;
}
}
public class Test {
public static void main(String[] args) {
AutoPlant autoPlant = new AutoPlant("汽车");
autoPlant.setName("汽车厂");
System.out.println(autoPlant.getName() + "生产的是" + autoPlant.productsName);
ShoeFactory shoeFactory = new ShoeFactory("鞋");
shoeFactory.setName("鞋厂");
System.out.println(shoeFactory.getName() + "生产的是" + shoeFactory.productsName);
}
}
```