From 59bc12c3f7c2996efb25b1ef799ebe5ba9372785 Mon Sep 17 00:00:00 2001 From: OrangeCat <73102364+tensorflow-jumao@users.noreply.github.com> Date: Wed, 28 Jul 2021 13:22:22 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E5=8F=82=E8=80=83=E7=AD=94?= =?UTF-8?q?=E6=A1=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Java/练习题:抽象类与接口.md | 123 +++++++++++++++++++++++++++++++++++ 1 file changed, 123 insertions(+) diff --git a/Java/练习题:抽象类与接口.md b/Java/练习题:抽象类与接口.md index c02ac8b..cf97ded 100644 --- a/Java/练习题:抽象类与接口.md +++ b/Java/练习题:抽象类与接口.md @@ -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); + } +} + +``` +