How can this code compile? The code below in the operator int CAN access a private variable of the class MyValue? Why?
class Program
{
static void Main(string[] args)
{
Myvalue my = new Myvalue(100);
Console.WriteLine(my + 100);
Console.Read();
}
}
public class Myvalue
{
private int _myvalue;
public Myvalue(int value)
{
_myvalue = value;
}
public static implicit operator int(Myvalue v)
{
return v._myvalue;
}
}
DR; TL; Yes it can.
The usual solution is to use a static member function to access the private static variable. A static member function is like a static member variable in that you can invoke it without an object being involved. Regular member functions can only be applied to an object and have the hidden "this" parameter.
Yes, we can have private methods or private static methods in an interface in Java 9. We can use these methods to remove the code redundancy. Private methods can be useful or accessible only within that interface only. We can't access or inherit private methods from one interface to another interface or class.
Your public/default static methods can still call your private statics.
Because it is in the class, it has access to private variables in it. Just like your instance public methods. It works the opposite way too. You can access private static members from instance members to create a Monostate pattern.
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