-2

Suppose i have the following class structure. If i execute the child class, it will print both.

Inside Public method

Inside Private method

Could anyone explain the reason how the private method code is reachable to m1 ?

class Base
{
    public void m1()
    {
        System.out.println("Inside Public method");
        m2();
    }


    private void m2()
    {
        System.out.println("Inside Private method");
    }
}


public class Child extends Base
{
    public static void main(String[] args)
    {
        Child ob = new Child();
        ob.m1();
    }
}
Community
  • 1
  • 1
Manasa
  • 72
  • 10
  • The private method is called from code in the same class. How where you expecting private methods, or fields, to be useful? – Tom Hawtin - tackline Mar 11 '20 at 15:01
  • Thinking from the other end... Who else other than a method from the same class call a private method? – Thiyagu Mar 11 '20 at 15:02
  • The private m2 method is a part of the same class that m1 lives in. Private methods can be called within the same class by other methods, even if they are public, but not in inherited classes. – WTFranklin Mar 11 '20 at 15:02
  • Because that is how private methods work: a method which can't be accessed by any other object outside the scope it is introduced. It can only be accessed by the same object/class – MT756 Mar 11 '20 at 15:02
  • I have no time too explain it, so I just point detail as comment... `m1() ` is in same scope as `m2()` – jabujavi Mar 11 '20 at 15:02
  • The top answer in the linked question has a good image on the differences, and it shows `private` as only accessible from the same `Class` (which these methods are). – Nexevis Mar 11 '20 at 15:03

4 Answers4

0

Private variables/methods are accessible by everything within the class.

Protected variables/methods are accessible by everything within that package and any subclasses.

Public variables/methods are accessible by everything.

MrsNickalo
  • 207
  • 1
  • 6
0

A private method is only visible in the class scope. The method m1 is in the same class as the private method m2 even if the m1 method is inherited.

Ismail
  • 2,322
  • 1
  • 12
  • 26
0

You can do this with a reflection, what you can see here:

Method method = c.getDeclaredMethod("m2", null);
      method.setAccessible(true);
      method.invoke(obj, null);

Any way to Invoke a private method?

Wesley
  • 61
  • 10
0

Private methods can be called by any method inside the class it is contained.

You can't call m2 method directly outside of the Base class scope, but you can call it indirectly through less restricted methods like public or protected. Like you did with m1 method.

The caller class could not call m1 directly, but it will certain execute it. This is known as encapsulation. You use it to hide implementation details that doesn't matter for the caller.