我有一個方形類,並且我想創建一個擴展並繼承所有方形類屬性的圓類......如何使圓類能夠做到這一點。將方形類繼承爲圓類
方形類有繪製,顏色,下降和大小屬性。我要如何圓類從廣場類
廣場類
package GamePackage;
import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.util.Random;
public class Square {
public int XLocation;
public int Size;
public int YLocation = -Size;
public int fallSpeed = 1;
Random rand = new Random();
int R = rand.nextInt((256-40)+1)+40;
int G = rand.nextInt((256-40)+1)+40;
int B= rand.nextInt((256-40)+1)+40;
Color RandomColour = new Color (R, G, B);
public int generateRandomXLocation(){
return XLocation = rand.nextInt(Game.WINDOW_WIDTH - Size);
}
/*
//creates a random value and stores it in squareWidth
*/
public int generateRandomSquareSize(){
return Size = rand.nextInt((30-17)+1)+17;
}
public int generateRandomFallSpeed(){
return fallSpeed = rand.ints(3, 3, 8).findFirst().getAsInt(); // 3, 3, 8
}
/*
//paints the square with the variables generated in the random methods
*/
public void paint(Graphics g){
g.setColor(RandomColour);
g.fillRect(XLocation,YLocation,Size,Size);
}
/*
//sets the squareWidth and square fallSpeed to a random value for every square created
*/
public Square(){
generateRandomXLocation();
generateRandomSquareSize();
generateRandomFallSpeed();
}
public void update(){
//changes the squares xLocation and fallSpeed if the created square reaches the bottom of the screen
if(YLocation >= Game.WINDOW_HEIGHT){
generateRandomXLocation();
generateRandomFallSpeed();
generateRandomSquareSize();
YLocation = -Size;
}
//moves the square down if the square is inside the window
if(YLocation <= Game.WINDOW_HEIGHT){
YLocation += fallSpeed;
}
}
public Rectangle GetBounds(){
Rectangle rectangle = new Rectangle(XLocation,YLocation,Size,Size);
return rectangle;
}
}
僅供參考:__從方塊開始的圓圈不聽起來不錯___。嘗試創建一個__Shape__類。然後從它繼承Square和Circle。 –
爲了遊戲的緣故,它們都是墜落的物體,它很有意義。 – Karavi
確切地說。 _「它們都是墜落的物體」或者「形狀」。不是正方形。圈子不能是方塊! –