Sunday, May 13, 2012

Java said, C# said. Static nested class


Java's static nested class, is mostly used for scoping needs:

// package-level is the default, there's no keyword to explicitly say so. This is analogous to C#'s internal
class Car {

    public int i = 7;

    Car() {
        Tire t = new Tire("Goodyear");
        Tire x = new Tire("Firemint");

        x.run();
        t.run();


    }

    private static class Tire {


        // package-level is the default. package-level is analogous to C#'s internal
        private String _s;

        // package-level is the default. there's no keyword to explicitly say so
        Tire(String s) {
            _s = s;
        }

        void run() {
            System.out.println("Hello " + _s);

            // cannot access i:
            // System.out.println(i);
        }
    }
}

The equivalent in C# :

// internal is the default, no need to explicitly say so
class Car {
    public int i = 7;
    
    // private is the default, explicitly say internal. analogous to java's package-level
    internal Car() {
        
        var t = new Tire("Goodyear");
        var x = new Tire("Firemint");


        x.Run();
        t.Run();

    }
    
    
    // internal is the default, explicit say private
    private class Tire {
        // private is the default no need to explicitly say so
        string _s; 
        
        // private is the default, explicitly say internal. analogous to java's package-level
        internal Tire(string s) {
            _s = s;
        }
        
        internal void Run() {
            Console.WriteLine ("Hello " + _s);
            
            // cannot access i:
            // Console.WriteLine (i);

        }
    }
}

No comments:

Post a Comment