标签:rect lin imp end package get The 标准 编程
实验四 类的继承
2.编程技巧
(1) 抽象类定义的方法在具体类要实现;
(2) 使用抽象类的引用变量可引用子类的对象;
(3) 通过父类引用子类对象,通过该引用访问对象方法时实际用的是子类的方法。可将所有对象存入到父类定义的数组中。
package java实验报告五;
public class Test1 {
public static void main(String[] args) {
Circle cir=new Circle(1);
Triangle tr=new Triangle(1,1,1);
Rectangle re=new Rectangle(1,1);
cir.getArea();
tr.getArea();
re.getArea();
}
}
package java实验报告五;
public class Circle extends Shape {
private double radius;
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
public Circle(double radius){
}
public double getArea(){
double Area=Math.PI*getRadius()*getRadius();
System.out.println("圆的面积:"+Area);
return Area;
}
}
package java实验报告五;
public class Rectangle extends Shape {
private double height;
private double width;
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public double getWidth() {
return width;
}
public void setWidth(double width) {
this.width = width;
}
public Rectangle(double height,double width){
this.height=height;
this.width=width;
}
public double getArea() {
double Area=getHeight()*getWidth();
System.out.println("矩形的面积:"+Area);
return Area;
}
}
package java实验报告五;
public class Triangle extends Shape {
private double a,b,c,p;
public double getA() {
return a;
}
public void setA(double a) {
this.a = a;
}
public double getB() {
return b;
}
public void setB(double b) {
this.b = b;
}
public double getC() {
return c;
}
public void setC(double c) {
this.c = c;
}
public double getP() {
return p;
}
public void setP(double p) {
this.p = p;
}
public Triangle(double a,double b,double c){
this.a=a;
this.b=b;
this.c=c;
}
public double getArea() {
p=(getA()+getB()+getC())/2;
double Area=Math.sqrt((p*(p-getA())*(p-getB())*(p-getC())));
System.out.println("三角形的面积:"+Area);
return Area;
}
}
package java实验报告五;
public class Test1 {
public static void main(String[] args) {
Circle cir=new Circle(1);
Triangle tr=new Triangle(1,1,1);
Rectangle re=new Rectangle(1,1);
cir.getArea();
tr.getArea();
re.getArea();
}
(二)使用接口技术
1定义接口Shape,其中包括一个方法size(),设计“直线”、“圆”、类实现Shape接口。分别创建一个“直线”、“圆”对象,将各类图形的大小输出。
(1) 接口中定义的方法在实现接口的具体类中要重写实现;
(2) 利用接口类型的变量可引用实现该接口的类创建的对象。
package java实验报告五demo2;
public interface Shape {
public void size();
}
package java实验报告五demo2;
class Line implements Shape {
public void size(){
System.out.println("生成一个直线");
}
}

package java实验报告五demo2;
public class Circle implements Shape {
public void size(){
System.out.println("生成一个圆");
}
}
package java实验报告五demo2;
public class Test1 {
public static void main(String[] args) {
Line l=new Line( );
l.size();
Circle c=new Circle();
c.size();
}

总结:本周学习了抽象类,接口,为抽象类,接口实例化,抽象类的模板设计,接口的制定标准。学起来有点吃力,我就有点烦
标签:rect lin imp end package get The 标准 编程
原文地址:https://www.cnblogs.com/hn010823/p/11684227.html