【发布时间】:2017-01-19 19:30:40
【问题描述】:
我有一个方形类,我想创建一个圆形类来扩展和继承所有方形类属性...我如何让圆形类做到这一点。
Square 类具有绘制、颜色、下降和大小属性。我如何让圆形类从方形类继承这些东西
方形类
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。
-
为了游戏,它们都是坠落的物体,这是有道理的
-
没错。 “它们都是坠落的物体” 或 形状。不是正方形。圆不能是正方形!
-
或者更好的是,使用组合而不是继承。
标签: java inheritance