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#?
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.
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.
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.
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.
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With