第七周实验
实验四 类的继承 实验内容 (1) 抽象类定义的方法在具体类要实现; (2) 使用抽象类的引用变量可引用子类的对象; (3) 通过父类引用子类对象,通过该引用访问对象方法时实际用的是子类的方法。可将所有对象存入到父类定义的数组中。 package zuoye01; abstract class shape { public abstract double print(); } class sanjiao extends shape { private double a; private double b; private double c; public sanjiao(double a,double b,double c){ this.a=a; this.b=b; this.c=c; } public double print() { double p=(a+b+c)/2; return Math.sqrt(p*(p-a)*(p-b)*(p-c)); } } class juxing extends shape { private double width; private double height; public juxing(double width,double height){ this.height=height; this.width=width; } public double print() { return width*height; } } class yuan extends shape { double radious; public yuan(double radious){ this.radious=radious; } public double print() { return Math.PI*radious*radious; } } public class zuoye01 { public static void main(String[] args){ shape s1=new sanjiao(3,4,5); shape s2=new juxing(5,8); shape s3=new yuan(6); System.out.println("三角形的面积为: "+s1.print()); System.out.println("矩形的面积为: "+s2.print()); System.out.println("圆的面积为: "+s3.print()); } } (二)使用接口技术 (1) 接口中定义的方法在实现接口的具体类中要重写实现; (2) 利用接口类型的变量可引用实现该接口的类创建的对象。 public interface Shape { } } } } public class zuoye02 { ``` (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |