(一)抽象类的使用
2.编程技巧
(1) 抽象类定义的方法在具体类要实现;
(2) 使用抽象类的引用变量可引用子类的对象;
(3) 通过父类引用子类对象,通过该引用访问对象方法时实际用的是子类的方法。可将所有对象存入到父类定义的数组中。
abstract class Shape{ private double area; public void area() { } } class Triangle extends Shape{ private double a; private double b; private double c; public Triangle(double a,double b,double c){ this.a = a; this.b = b; this.c = c; } public void area() { double p=(a+b+c)/2; double s = p*(p-a)*(p-b)*(p-c); double result = Math.sqrt(s); System.out.println("三角形的面积为"+result); } } class Rectangle extends Shape{ private double height; private double width; public Rectangle(double height,double width){ this.height = height; this.width = width; } public void area() { double sm =(height*width); System.out.println("矩形面积为"+sm); } } class Circle extends Shape{ private double r; public Circle(double r){ this.r = r; } public void area() { double cm =Math.PI *Math.pow(r, 2); System.out.println("圆形面积为"+cm); } } public class Z { public static void main (String [] args){ Shape triangle = new Triangle(15.0,16.0,8.0); Shape rectangle = new Rectangle(4.0,7.0); Shape circle = new Circle(3.0); triangle.area(); rectangle.area(); circle.area(); } }
结果截图
(二)使用接口技术
1定义接口Shape,其中包括一个方法size(),设计“直线”、“圆”、类实现Shape接口。分别创建一个“直线”、“圆”对象,将各类图形的大小输出。
2.编程技巧
(1) 接口中定义的方法在实现接口的具体类中要重写实现;
(2) 利用接口类型的变量可引用实现该接口的类创建的对象。
实验代码
interface Shape { public void size(); } class StraightLine implements Shape{ private double length; public StraightLine(double s) { this.length = s; } public void size() { System.out.println("直线的长度为"+this.length+"cm"); } } class Circle implements Shape{ private double a; private double area; public Circle(double r) { this.a=r; this.area=Math.PI*Math.pow(r,2); } public void size() { System.out.println("圆的半径为"+this.a+" 圆的面积大小为"+this.area); } } public class C { public static void main (String args[]) { Shape form=new StraightLine(20); Shape form2=new Circle(5); form.size(); form2.size(); } }
结果截图
本周总结
本周学习了抽象类与接口的应用
在Java中可以通过对象的多态性为抽象类和接口实例化;接口是Java解决多继承局限的一种手段。
原文:https://www.cnblogs.com/zcl666/p/11657173.html