java新手静态的问题
PHP中文网
PHP中文网 2017-04-17 13:32:35
0
2
289

初学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));
    }
}
  1. public static double area(double r){    
    return Math.PI*r*r;
    

    }
    这个静态方法能够被主函数引用吗?为什么?

  2. System.out.println(c1.area());    //
    System.out.println(Circle.area(2.5));
    System.out.println(Circle.area(c1));
    

    这三次调用不用方法,第一个必须是实例吗?另外第二个和第三个调用为什么是Circle。area()?Circle是不是声明类啊?


小白问题求解,谢谢!!!
PHP中文网
PHP中文网

认证高级PHP讲师

reply all(2)
小葫芦

The first c1.area() calls the instance method
The latter two calls are static methods.

Your main is defined in class ex_6. To access the static method of Circle, of course you must specify which class it is, so it will be Circle.area(...)

If you define a static method in ex_6, you do not need to prefix the class name when calling it in main. Of course, it is also correct if the class name is prefixed. Like this

javapublic class ex_6{
    private static void Test() {
        System.out.println("hello test");
    }

    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));

        Test();
        ex_6.Test();
    }
}
黄舟

Can 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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template