Java面向对象程序设计考试题目 类的定义 继承 创建对象 构造方法

2025-04-06 14:14:17
推荐回答(2个)
回答1:

public class Geometry {
public Geometry(int w, int h) {
width = w;
height = h;
}
public int area() {
return width * height;
}
private int width, height;
}
public class Cube extends Geometry {
public Cube(int w, int h) {
super(w, h);
}
public Cube(int a, int b, int c) {
super(a, b);
height = c;
}
public void setHeight(int h) {
height = h;
}
public int volumn() {
return area() * height;
}
private int height;
}
public class User {
public static void main(String []args) {
Cube cube1 = new Cube(1,2,3);
Cube cube2 = new Cube(4, 5);
cube2.setHeight((int) (Math.random() * 10) + 1);//avoid zero height
System.out.println("Cube 1 area: " + cube1.area() + " volumn: " + cube1.volumn());
System.out.println("Cube 2 area: " + cube2.area() + " volumn: " + cube2.volumn());
}
}

回答2:

测试类: public class MyPointTest { public static void main(String[] args) { MyPoint m=new MyPoint(2,3); System.out.println(m.distance(3, 4)); } } MyPoint类 public class MyPoint { private int x; private int y; public MyPoint(){ } public MyPoint(int x,int y){ this.x=x; this.y=y; } public void setX(int x){ this.x=x; } public int getx(){ return x; } public void setY(int y){ this.y=y; } public int getY(){ return y; } public double distance(int x,int y){ return Math.sqrt((this.x-x)*(this.x-x)+(this.y-y)*(this.y-y)); } }