Java-使用来自另一个类的方法
我有以下代码:Java-使用来自另一个类的方法,java,Java,我有以下代码: interface Paint { float paintPerSurfaceUnit = (float) 0.3; } class PaintThings implements Paint { public float paint_sphere(Sphere obj){ return (obj.area() * paintPerSurfaceUnit); } } class Sphere extends Shape
interface Paint {
float paintPerSurfaceUnit = (float) 0.3;
}
class PaintThings implements Paint {
public float paint_sphere(Sphere obj){
return (obj.area() * paintPerSurfaceUnit);
}
}
class Sphere extends Shape {
int radius;
public float area(){
return (float) (4*3.14*radius*radius);
}
}
如何使用sphere对象访问main中的“paint_sphere?”您必须使用一个
PaintThings
的实例
public static void main(String[] args){
Sphere sphere = new Sphere();
PaintThings paintthings = new PaintThings();
paintthings.paint_sphere(sphere);
}
确保将
球体
传递到绘制球体(球体)
方法。这里有两种选择:要么让你的函数是静态的
class PaintThings implements Paint {
static public float paint_sphere(Sphere obj){
return (obj.area() * paintPerSurfaceUnit);
}
}
就这样说吧
mySphere sphere = new Sphere();
PaintThings.paintSphere(yourSphere);
或者也制作一个绘画对象:
PaintThings myPainter = new PaintThings();
mySphere sphere = new Sphere();
myPainter.paint_sphere(mySphere);
您可以尝试以下代码,方法paint实例化PaintThings并通过此
class Sphere extends Shape {
int radius;
public float area(){
return (float) (4*3.14*radius*radius);
}
public float paint(){
return new PaintThings().paint_sphere(this);
}
但是更好的方法是通过构造函数传递PaintThing对象以减少耦合
class Sphere extends Shape {
int radius;
Paint paint;
Sphere(Paint paint){
this.paint = paint;
}
public float area(){
return (float) (4*3.14*radius*radius);
}
public float paint(){
return paint.paint_sphere(this);
}
您需要一个带有球体类或对象的
PaintThings
实例?new PaintThings()代码>其中mySphere
是您的球体对象。对象,Sphere bigBall=new Sphere();我不想让PaintThink对象,我想在系统打印中使用什么意思?什么是系统打印?如果paint_sphere();正如@Arijoon所说,使用我的第一个解决方案,并使paintPerSurfaceUnit
static,但这很奇怪……他不想使用两个类是的!非常好,非常感谢!,我想要痛苦的形状而不是画画这值得一个金色的脸谱