我在理解繼承如何在Java中工作時遇到問題。我有3個相互延伸的類。第三課是我遇到問題的棘手問題。繼承和抽象如何與多個類一起工作? [java]
public abstract class Shape{
//methods and variables
protected final static int X_MAX_SIZE = 800;
protected final static int Y_MAX_SIZE = 600;
private int xCord;
private int yCord;
public void setX(int newX){
if(newX > 0 && newX < 800){
this.xCord = newX;
}
else {
System.out.println("Invalid size.");
this.xCord = 0;
}
}
public int getX(){
return xCord;
}
public void setY(int newY){
if(newY > 0 && newY < 600){
this.yCord = newY;
}
else{
System.out.println("Invalid size.");
this.yCord = 0;
}
}
public int getY(){
return yCord;
}
public Shape(){
}
public Shape(int xCord, int yCord){
}
abstract void display();
abstract double area();
}
public class Rectangle extends Shape {
// the inherited methods and calculations
int width, height;
public int getHeight(){
return height;
}
public void setHeight(int newHeight){
this.height = newHeight;
}
public int getWidth(){
return width;
}
public void setWidth(int newWidth){
this.width = newWidth;
}
public Rectangle(){
}
public Rectangle(int x, int y, int height, int width){
setX(x);
setY(y);
setHeight(height);
setWidth(width);
}
@Override
void display(){
String toScreen = "Rectangle X: " + getX() + "\nRectangle Y: " + getY();
String toScreenInfo = "\nRectangle height: " + getHeight() + "\nRectangle Width:getWidth();
String toScreenArea = "\nRectangle area: " + area();
System.out.println(toScreen + toScreenInfo + toScreenArea);
}
@Override
double area(){
return (width * height);
}
}
}
public class Square extends Rectangle {
// more methods, but no new variables. & calculations
public Square(int x, int y, int height, int width){
setX(x);
setY(y);
setHeight(height);
setWidth(width);
}
public Square(){
super();
}
@Override
public void setHeight(int height){
if(height != getWidth()){
height = getWidth();
}
}
@Override
public void setWidth(int width){
if(width != getHeight()){
width = getHeight();
}
}
@Override
double area(){
return (width * height);
}
@Override
void display(){
String toScreen = "Square area is " + area();
}
}
}
類廣場我甚至有麻煩,甚至在主要調用。 所以我在這裏的目標是改變Square類的值,以確保'高度'和'寬度'彼此相等以形成一個正方形。我的約束無法在get/set和構造函數中創建任何新變量。
嗯,你認爲我們是介意讀者嗎?沒有任何人提供足夠的信息來幫助你。 – ajb 2014-12-07 04:31:24
這是所有的代碼是什麼?還是有更多的代碼與你一起工作可能會導致你遇到的問題?而且,究竟是什麼問題呢? – 2014-12-07 04:32:23
你需要發佈一個實際產生你聲稱收到的結果的例子。 – csmckelvey 2014-12-07 04:33:47