我目前正在开发一个简单的Java游戏,有几种不同的模式.我扩展了一个主要的Game类,将主要逻辑放在其他类中.尽管如此,主要的游戏类仍然非常沉重.
在快速浏览一下我的代码后,其中大部分是Getters and Setters(60%),而其余部分则是游戏逻辑真正需要的.
一些谷歌搜索声称Getters和Setters是邪恶的,而其他人声称他们是良好的OO练习和伟大的程序所必需的.
所以我该怎么做?应该是哪个?我应该为我的私人变量更改我的Getters和Setter,还是应该坚持使用它们?
class Dad
{
protected static String me = "dad";
public void printMe()
{
System.out.println(me);
}
}
class Son extends Dad
{
protected static String me = "son";
}
public void doIt()
{
new Son().printMe();
}
Run Code Online (Sandbox Code Playgroud)
功能doIt将打印"爸爸".有没有办法让它打印"儿子"?
public class Circle {
public float r = 100;
public float getR() {
return r;
}
}
public class GraphicCircle extends Circle {
public float r = 10;
public float getR() {
return r;
}
// Main method
public static void main(String[] args) {
GraphicCircle gc = new GraphicCircle();
Circle c = gc;
System.out.println("Radius = " + gc.r);
System.out.println("Radius = " + gc.getR());
System.out.println("Radius = " + c.r);
System.out.println("Radius = " + c.getR());
}
}
Run Code Online (Sandbox Code Playgroud)
嗨,我在理解上面代码的输出时遇到了麻烦。输出为:
Radius = 10.0
Radius …Run Code Online (Sandbox Code Playgroud) 我有这4个java clases:1
public class Rect {
double width;
double height;
String color;
public Rect( ) {
width=0;
height=0;
color="transparent";
}
public Rect( double w,double h) {
width=w;
height=h;
color="transparent";
}
double area()
{
return width*height;
}
}
Run Code Online (Sandbox Code Playgroud)
2
public class PRect extends Rect{
double depth;
public PRect(double w, double h ,double d) {
width=w;
height=h;
depth=d;
}
double area()
{
return width*height*depth;
}
}
Run Code Online (Sandbox Code Playgroud)
3
public class CRect extends Rect{
String color;
public CRect(double w, double h ,String c) { …Run Code Online (Sandbox Code Playgroud) java ×4
inheritance ×2
accessor ×1
getter ×1
oop ×1
overriding ×1
polymorphism ×1
setter ×1
subclass ×1
superclass ×1