Does the order of declaration matter in Java/C#?

2020-02-06 02:38发布

In C++ I can't use a method if I declare it after the calling method.

Does this order matter in other languages like Java or C#?

标签: java c#
12条回答
仙女界的扛把子
2楼-- · 2020-02-06 03:13

The order of methods/constructors does matter in Java in some corner cases:

class Callee {
    private static void bar(int i) { } // compilation error if first
    public static void bar(String s) { } // ok if this method is first
}

class Caller {
    private void foo() { Callee.bar(bar()); }
    private <T> T bar() { return null; }
}
查看更多
混吃等死
3楼-- · 2020-02-06 03:14

No .

查看更多
时光不老,我们不散
4楼-- · 2020-02-06 03:14

It doesn't in C#.

查看更多
祖国的老花朵
5楼-- · 2020-02-06 03:18

neither C# nor Java does.

查看更多
在下西门庆
6楼-- · 2020-02-06 03:20

Declaration order of methods never matters in C# or Java. Likewise it doesn't matter whether you declare a method before or after a variable that it uses.

Declaration order of variables can matter, however, when they're initialized one depends on another. For example (C#):

using System;

class Test
{
    static int x = 5;
    static int y = x;

    static void Main()
    {
        // Prints x=5 y=5
        Console.WriteLine("x={0} y={1}", x, y);
    }
}

but:

using System;

class Test
{
    static int y = x;
    static int x = 5;

    static void Main()
    {
        // Prints x=5 y=0
        Console.WriteLine("x={0} y={1}", x, y);
    }
}

Java prevents this exact situation, but it's easy to mimic:

public class Test
{
    static int y = getInitialValue();
    static int x = 5;

    public static void main(String args[])
    {
        System.out.println("x=" + x + " y=" + y);
    }

    static int getInitialValue()
    {
        return x;
    }
}

In C# things become even more confusing when you involve partial classes. Initialization occurs in textual order in C#, but that order isn't fully defined when you have multiple files contributing to the same class.

Needless to say, avoid this wherever you possibly can!

查看更多
孤傲高冷的网名
7楼-- · 2020-02-06 03:22

There is one tricky case where lexically the function to be called can be declared after the point of call, but not semantically. This is because the class is deemed to be completely defined in the body of the class member functions.

$9.2.2 - "A class is considered a completely-defined object type (3.9) (or complete type) at the closing } of the class-specifier. Within the class member-specification, the class is regarded as complete within function bodies, default arguments and constructor ctor-initializers (including such things in nested classes). Otherwise it is regarded as incomplete within its own class member-specification."

struct A{
    void f(){g();}    // OK to call 'g' even if the compiler has not seen 'g' as yet
    void g(){};
};

int main(){
    A a;
    a.f();
}
查看更多
登录 后发表回答