non-final
、静态和非静态变量。接口只有静态和最终变量。implements
”来实现,抽象类可以使用关键字“extends
”进行扩展。import java.io.*; abstract class Shape { String objectName = " "; Shape(String name) { this.objectName = name; } public void moveTo(int x, int y){ System.out.println(this.objectName + " " + "已移至" + " x = " + x + " and y = " + y); } abstract public double area(); abstract public void draw(); } class Rectangle extends Shape { int length, width; Rectangle(int length, int width, String name){ super(name); this.length = length; this.width = width; } @Override public void draw(){ System.out.println("矩形已绘制"); } @Override public double area(){ return (double)(length * width); } } class Circle extends Shape { double pi = 3.14; int radius; Circle(int radius, String name){ super(name); this.radius = radius; } @Override public void draw(){ System.out.println("圆形已绘制"); } @Override public double area(){ return (double)((pi * radius * radius) / 2); } } class HY { public static void main(String[] args){ Shape rect = new Rectangle(2, 3, "Rectangle"); System.out.println("矩形面积:" + rect.area()); rect.moveTo(1, 2); System.out.println(" "); Shape circle = new Circle(2, "Circle"); System.out.println("圆的面积:" + circle.area()); circle.moveTo(2, 4); } }
输出:
矩形面积:6.0
矩形已移至 x = 1 和 y = 2
圆的面积:6.28
圆已移至 x = 2 和 y = 4
如果我们在矩形和圆形之间没有任何通用代码,请使用界面。
import java.io.*; interface Shape { void draw(); double area(); } class Rectangle implements Shape { int length, width; Rectangle(int length, int width){ this.length = length; this.width = width; } @Override public void draw(){ System.out.println("矩形已绘制"); } @Override public double area(){ return (double)(length * width); } } class Circle implements Shape { double pi = 3.14; int radius; Circle(int radius) { this.radius = radius; } @Override public void draw(){ System.out.println("圆形已绘制"); } @Override public double area(){ return (double)((pi * radius * radius) / 2); } } class HY { public static void main(String[] args){ Shape rect = new Rectangle(2, 3); System.out.println("矩形面积:" + rect.area()); Shape circle = new Circle(2); System.out.println("圆的面积:" + circle.area()); } }
输出:
矩形面积:6.0
圆的面积:6.28
什么时候用什么?
如果以下任何陈述适用于您的情况,请考虑使用抽象类:
java
应用程序中,有一些相关的类需要共享一些代码行,那么你可以将这些代码行放在抽象类中,并且这个抽象类应该由所有这些相关类进行扩展。public
之外的访问修饰符(例如 protected
和 private
)。如果以下任何陈述适用于您的情况,请考虑使用接口: