Is declaration order in Java / C #?

In C ++, I cannot use a method if I declare it after a method call.

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

+3
source share
12 answers

No.

+23
source

The order in which the methods are written never matters in C # or Java. It also doesn't matter if you declare the method before or after the variable that it uses.

The order values ​​of the variables may matter, however, when they are initialized, each depends on the other. 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);
    }
}

a

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 is easy to imitate:

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

# , . #, , , .

, , .

+22

Java, # .

. , eachother, .

+2

, .

+2

Java 1 () Java ( "JLS", 3- , ):

, .

+1

#, java .

0

#.

0

#, Java .

0

, . , .

0

, ​​ , . , - .

$9.2.2 - " (3.9) ( ) } . -, , ctor- ( ). -".

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();
}
0

/ Java :

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; }
}
0

, . , , .. , , . , , , , main . , , , ( , , ). , , , , (, ). :

   final List<int[]> intArrays = Arrays.stream(testarray).collect(Collectors.toList());
   final List<Integer> integers = intArrays.stream().flatMap(z -> 
                  Arrays.stream(z).boxed()).collect(Collectors.toList());

unless you add comments like:
final List<int[]> intArrays = Arrays.stream(testarray).collect(Collectors.toList());
// this makes a List (of ints) variable type that cannot be changed based on the stream of 
//(the testarray in this case) and uses the Collector method to add the ints
//to intArrays (our variable name)
final List<Integer> integers = intArrays.stream().flatMap(z -> 
                  Arrays.stream(z).boxed()).collect(Collectors.toList());
// I would have to look this up, because I honestly have no clue what it does exactly. 

As I said, the code is mostly gibberish. Help yourself and everyone who can look at your code and write it in a logical order, no matter what language you use. (And again, please use the comments! You will thank me later.)

0
source

Source: https://habr.com/ru/post/1703483/


All Articles