前言:
数据抽象是一种仅向用户显示基本细节的属性。不向用户显示琐碎或非必需的单元。例如:汽车被视为汽车而不是其单个组件。
数据抽象也可以定义为仅识别对象所需特征而忽略不相关细节的过程。对象的属性和行为将其与其他类似类型的对象区分开来,也有助于对对象进行分类/分组。
考虑一个男人开车的真实例子。男人只知道踩油门会提高车速或踩刹车会停车,但他不知道踩油门车速实际上是如何增加的,他不知道汽车的内部机制汽车或在汽车中执行油门、刹车等。这就是抽象。
在java中,抽象是通过接口和抽象类来实现的。我们可以使用接口实现 100% 的抽象。
在某些情况下,我们希望定义一个超类来声明给定抽象的结构,而无需提供每个方法的完整实现。也就是说,有时我们会想要创建一个只定义一个泛化形式的超类,该泛化形式将被其所有子类共享,而将其留给每个子类来填充细节。
考虑一个经典的“形状”示例,可能用于计算机辅助设计系统或游戏模拟。基本类型是“形状”,每个形状都有颜色、大小等。由此,衍生出(继承)特定类型的形状——圆形、方形、三角形等——每一种都可能有额外的特征和行为。例如,某些形状可以翻转。某些行为可能会有所不同,例如当您要计算形状的面积时。类型层次体现了形状之间的相似性和差异性。
abstract class Shape { String color; abstract double area(); public abstract String toString(); public Shape(String color){ System.out.println("Shape constructor called"); this.color = color; } public String getColor() { return color; } } class Circle extends Shape { double radius; public Circle(String color, double radius){ super(color); System.out.println("Circle constructor called"); this.radius = radius; } @Override double area(){ return Math.PI * Math.pow(radius, 2); } @Override public String toString(){ return "Circle color is " + super.getColor() + "and area is : " + area(); } } class Rectangle extends Shape { double length; double width; public Rectangle(String color, double length,double width){ super(color); System.out.println("Rectangle constructor called"); this.length = length; this.width = width; } @Override double area() { return length * width; } @Override public String toString(){ return "Rectangle color is " + super.getColor() + "and area is : " + area(); } } public class Test { public static void main(String[] args){ Shape s1 = new Circle("Red", 2.2); Shape s2 = new Rectangle("Yellow", 2, 4); System.out.println(s1.toString()); System.out.println(s2.toString()); } }
输出:
Shape constructor called
Circle constructor called
Shape constructor called
Rectangle constructor called
Circle color is Redand area is : 15.205308443374602
Rectangle color is Yellowand area is : 8.0