在
Java 基础教程中,
案例4-3通常涉及创建一个简单的"Shape"(形状)抽象类和它的两个子类,比如"Circle"(圆形)和"Squre"(正方形)。这个例子展示了面向对象编程中的基本概念,如封装、继承和多态。
java// java 基础案例 Shape抽象类
abstract class Shape {
// 定义抽象方法
abstract void draw();
}
// Circle子类
class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
void draw() {
System.out.println("Drawing a circle with radius " + radius);
}
}
// Square子类
class Square extends Shape {
private double side;
public Square(double side) {
this.side = side;
}
@Override
void draw() {
System.out.println("Drawing a square with side length " + side);
}
}
public class Main {
public static void main(String[] args) {
// 创建并绘制实例
Shape circle = new Circle(5);
circle.draw(); // 输出: Drawing a circle with radius 5
Shape square = new Square(10);
square.draw(); // 输出: Drawing a square with side length 10
}
}
版权声明:
本文来源网络,所有图片文章版权属于原作者,如有侵权,联系删除。
本文网址:https://www.bianchenghao6.com/h6javajc/70.html