面试题答案
一键面试- 抽象类定义:
- 定义一个抽象类
Shape
,它作为所有图形类的基类。在Java中,使用abstract
关键字来定义抽象类。
abstract class Shape { // 抽象类可以包含成员变量 protected String color; // 构造函数 public Shape(String color) { this.color = color; } // 抽象方法,具体实现由子类完成 public abstract void draw(); }
- 定义一个抽象类
- 抽象方法:
- 在上述
Shape
抽象类中,draw
方法被声明为抽象方法。抽象方法只有方法声明,没有方法体,使用abstract
关键字修饰。抽象方法强制要求子类必须实现该方法,这样可以保证所有具体图形类都有绘制自身的能力。
- 在上述
- 具体图形类实现抽象方法:
- 圆形类:
class Circle extends Shape { private double radius; public Circle(String color, double radius) { super(color); this.radius = radius; } @Override public void draw() { System.out.println("Drawing a " + color + " circle with radius " + radius); } }
- 矩形类:
class Rectangle extends Shape { private double width; private double height; public Rectangle(String color, double width, double height) { super(color); this.width = width; this.height = height; } @Override public void draw() { System.out.println("Drawing a " + color + " rectangle with width " + width + " and height " + height); } }
在上述代码中,Circle
和Rectangle
类继承自Shape
抽象类,并实现了draw
抽象方法,从而能够根据自身特性完成绘制操作。