Java:定义父类Point,包含两个成员变量x,y和参数的构造方法,子类Point3D增加一个静态变量c用来统计主类中

2024-12-29 21:31:19
推荐回答(2个)
回答1:

//Point.java

public class Point {

private int x;
private int y;

public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public Point(int x, int y) {
this.x=x;
this.y=y;
}

}

//Rectangle.java
public class Rectangle extends Point{

private int x;
private int y;
private int width;
private int height;

public Rectangle(int x, int y) {
super(x, y);
// TODO Auto-generated constructor stub
}
public Rectangle(int x2, int y2, int width, int height) {
super(x2, y2);
this.x = x2;
this.y = y2;
this.width = width;
this.height = height;
}

public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}

}

//Cube.java

public class Cube extends Point{

private int x;
private int y;
private int z;
private int length;
private int width;
private int heigth;

public Cube(int x, int y, int z, int length, int width,
int heigth) {
super(x, y);
x = x;
y = y;
this.z = z;
this.length = length;
this.width = width;
this.heigth = heigth;
}

public int getLength() {
return length;
}
public void setLength(int length) {
this.length = length;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeigth() {
return heigth;
}
public void setHeigth(int heigth) {
this.heigth = heigth;
}
public int getZ() {
return z;
}
public void setZ(int z) {
this.z = z;
}

}

//测试类T.java
import java.awt.*;
import java.awt.event.*;

public class T{

public static void main(String args[]) {
Point p = new Point(1,2);
Rectangle r = new Rectangle(5,5,200,300);
Cube c = new Cube(10,10,10,15,10,25);

System.out.print("长方形的位置、长、宽分别为:");
System.out.println("("+r.getX()+","+r.getY()+")、"+r.getWidth()+"、"+r.getHeight());
System.out.print("立方体的位置、长、宽、高分别为:");
System.out.println("("+c.getX()+","+c.getY()+","+c.getZ()+")、"+c.getLength()+"、"+c.getWidth()+"、"+c.getHeigth());

}
}

您的进步是我最大的动力,如果你觉得我回答的合理的话,请给我多加分。谢谢,如果不明白的话,大家相互学习啊!

如果对您有帮助,请记得采纳为满意答案,谢谢!祝您生活愉快!

vaela

回答2:

图显IP:
1和2:
package net.jackshow.parent;

public class Point {

private String x;
private String y;

/**
* 默认构造函数
*/
public Point(){

}

public String getX() {
return x;
}

public void setX(String x) {
this.x = x;
}

public String getY() {
return y;
}

public void setY(String y) {
this.y = y;
}
}

package net.jackshow.child;

import net.jackshow.parent.Point;

public class Point3D extends Point{

static int c=0;

public Point3D(){
super();
c++;
}

public static void main(String[] args){
Point3D child = new Point3D();
Point3D child1 = new Point3D();
System.out.println("x="+child.getX()+",y="+child.getY()+",c="+c);
}
}

第3,你在class前面加上abstract,接口则把class改为interface,然后变量全部改为public的