问答题

【说明】下面的程序先构造Point类,再顺序构造Ball类。由于在类Ball中不能直接存取类Point中的xCoordinate及yCoordinate属性值,Ball中的toString方法调用Point类中的toString方法输出中心点的值。在MovingBall类的toString方法中,super.toString调用父类Ball的toString方法输出类Ball中声明的属性值。 public class Point { private double xCoordinate; private double yCoordinate; public Point 0 } public Point(ouble x, double y) { xCoordinate = x; yCoordinate = y; } public String toString() { return "( + Double.toString(Coordinate)+ "," + Double.toString(Coordinate) + "); } //other methods } public class Ball { (1) ; //中心点 private double radius; //半径 private String colour; ///颜色 public Ball() { } public Ball(double xValue, double yValue, double r)// 具有中心点及半径的构造方法 { center= (2) ;//调用类Point 中的构造方法 radius = r; } public Ball(double xValue, double yValue, double r, String c) // 具有中心点、半径及颜色的构造方法 { (3) ;//调用3个参数的构造方法 colour = c; } public String toString() { return "A ball with center" + center, toString() + ", radius" + Double.toString(radius) + ", colour" + colour; } //other methods } public class MovingBall. (4) { private double speed; public MovingBall() { } public MovingBall(double xValue, double yValue, double r, String e, double s) { (5) ;// 调用父类Ball中具有4个参数的构造方法 speed = s; } public String toString( ) { return super, toString( ) + ", speed "+ Double.toString(speed); } //other methods } public class Tester{ public static void main(String args[]){ MovingBall mb = new MovingBall(10,20,40,"green",25); System.out.println(mb); } }

【参考答案】

[解析] (1)private Point center Ball类以Point类的center对象作为私有成员。 (......

(↓↓↓ 点击下方‘点击查看答案’看完整答案 ↓↓↓)
热门 试题

问答题
【说明】C++语言本身不提供对数组下标越界的判断。为了解决这一问题,在程序6中定义了相应的类模板,使得对厂任意类型的二维数组,可以在访问数组元素的同时,对行下标和列下标进行越界判断,并给出相应的提示信息。#include<iostream.h>template <class T> class Array;template <class T> class ArrayBody {friend (1) T* tpBody;int iRows, iColumns, iCurrentRow;ArrayBody (int iRsz, int iCsz) {tpBody = (2) iRows = iRsz; iColumns =iCsz; iCurrentRow =-1;}public:T& operator[] (int j) {bool row_error, column_error;row_error=column_error=false;try{if (iCurrentRow < 0 || iCurrentRow >=iRows)row_error=true;if (j < 0 || j >=iColumns)column_error=true;if ( row_error==true || column_error == true)(3) }catch (char) {if (row_error==true)cerr << 行下标越界[ << iCurrentRow << ] ;if (column_error== true )cerr << 列下标越界[ <<j << ] ;cout << n ;}return tpBody[iCurrentRow * iColumns +j];};~ArrayBody ( ) { delete[] tpBody; }};template <class T> class Array {ArrayBody<T> tBody;public:ArrayBody<T> & operator[] (int i) {(4) return tBody;}Array (int iRsz, int iCsz) : (5) {}};void main(){ Array<int>a1(10,20);Array<double>a2(3,5);int b1;double b2;b1=a1[-5][10]; 有越界提示:行下标越界[-5]b1=a1[10][15]; 有越界提示:行下标越界[10]b1=a1[1][4]; 没有越界提示b2=a2[2][6]; 有越界提示:列下标越界[6]b2=s2[10][20]; 有越界提示:行下标越界[10]列下标越界[20]b2=a2[1][4]; 没有越界提示}