Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java inner classes in c#

I have the following Java code:

public class A {
    private int var_a = 666;

    public A() {
        B b = new B();
        b.method123();
        System.out.println(b.var_b);
    }

    public class B {
        private int var_b = 999;

        public void method123() {
            System.out.println(A.this.var_a);           
        }
    }
}

Which yields 666 and 999. Now, I've tried to set up similar code in c#, but it seems that it is not possible to accomplish the same. If that's the case, how you usually achieve a similar effect when programming in c#?

like image 231
devoured elysium Avatar asked Mar 02 '10 21:03

devoured elysium


People also ask

What is an inner class in Java?

Java inner class or nested class is a class that is declared inside the class or interface. We use inner classes to logically group classes and interfaces in one place to be more readable and maintainable. Additionally, it can access all the members of the outer class, including private data members and methods.

Can a Java class contain inner class?

In Java, just like methods, variables of a class too can have another class as its member. Writing a class within another is allowed in Java. The class written within is called the nested class, and the class that holds the inner class is called the outer class.

What is nested class with example?

A nested class is a class that is declared in another class. The nested class is also a member variable of the enclosing class and has the same access rights as the other members. However, the member functions of the enclosing class have no special access to the members of a nested class.

What are nested and inner classes?

In Java programming, nested and inner classes often go hand in hand. A class that is defined within another class is called a nested class. An inner class, on the other hand, is a non-static type, a particular specimen of a nested class.


2 Answers

You need to make the inner class take an instance of the outer class as a constructor parameter. (This is how the Java compiler implements inner classes)

like image 189
SLaks Avatar answered Sep 21 '22 17:09

SLaks


Inner classes are handled slightly differently between C# and Java. Java implicitly passes a reference to an instance of the outer class to the inner class, allowing the inner class to access fields of the outer class. To gain similar functionality in C#, you just have to do explicitly what Java does implicitly.

Check out this article for some more information.

like image 40
Corey Sunwold Avatar answered Sep 20 '22 17:09

Corey Sunwold