If I have ObjectA, and it has a private method GetPrice()
and also has a "parent" field of the same type, why am I able to call GetPrice()
on the parent instance from within the child instance?
Example:
private decimal GetPrice()
{
ObjectA parent = Parent;
if(parent != null)
{
return parent.GetPrice(); // Why is this OK?
}
return 0;
}
We can call the private method of a class from another class in Java (which are defined using the private access modifier in Java). We can do this by changing the runtime behavior of the class by using some predefined methods of Java. For accessing private method of different class we will use Reflection API.
You can call the private method from outside the class by changing the runtime behaviour of the class.
You can access private members from any code block that is defined in the same class. It doesn't matter what the instance is, or even if there is any instance (the code block is in a static context). But you cannot access them from code that is defined in a different class.
Private Methods can only be used inside the class. To set private methods, use the private access specifier. Private access specifier allows a class to hide its member variables and member functions from other functions and objects. Only functions of the same class can access its private members.
Object users can't use private methods directly. The main reason to do this is to have internal methods that make a job easier.
Because private means "not accessible to other types", not "not accessible to other instances".
Because private
scope is limited to the class, not the instance as defined in the C# spec:
1.6.2 Accessibility Each member of a class has an associated accessibility, which controls the regions of program text that are able to access the member. There are five possible forms of accessibility. These are summarized in the following table.
Accessibility Meaning public Access not limited protected Access limited to this class or classes derived from this class internal Access limited to this program protected internal Access limited to this program or classes derived from this class private Access limited to this class
An access modifier is related to it's implementing class/type not to instances of that class
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