初学java,静态方法这边有些疑惑。
class Circle{
double r;
public Circle(double r){
this.r=r;
}
public double area(){
return Math.PI*r*r;
}
public static double area(double r){ //1.主函数能引用这个静态方法吗?
return Math.PI*r*r;
}
public static double area(Circle c){
return Math.PI*c.r*c.r;
}
}
public class ex_6{
public static void main(String[] args){
Circle c1 = new Circle(2);
System.out.println(c1.area()); //
System.out.println(Circle.area(2.5));
System.out.println(Circle.area(c1));
}
}
public static double area(double r){
return Math.PI*r*r;
}
这个静态方法能够被主函数引用吗?为什么?
System.out.println(c1.area()); //
System.out.println(Circle.area(2.5));
System.out.println(Circle.area(c1));
这三次调用不用方法,第一个必须是实例吗?另外第二个和第三个调用为什么是Circle。area()?Circle是不是声明类啊?
小白问题求解,谢谢!!!
The first
c1.area()
calls the instance methodThe latter two calls are static methods.
Your
main
is defined in classex_6
. To access the static method ofCircle
, of course you must specify which class it is, so it will beCircle.area(...)
If you define a static method in
ex_6
, you do not need to prefix the class name when calling it inmain
. Of course, it is also correct if the class name is prefixed. Like thisCan this code be compiled?
This static method uses non-static member variables, and it feels like it should be compiled but it won’t pass