1

Why I am getting 4, when base class function fun(int) is private and 5 if its default?.

class one 
{
    int a;  
    private void fun(int a)
    {
        System.out.println(a);
    }


    public static void main (String [] args)
    {
        one y= new B();
        y.fun(4);
        //  B obj =new B(); 
        //  obj.fun(4);
    }   
}

class B extends one
{
   void fun(int a)
    {
        a = a+1;
        System.out.println(a);
    }
}
Kara
  • 5,650
  • 15
  • 48
  • 55
Batty
  • 111
  • 1
  • 5

1 Answers1

0

See the Java specification, the chapter 8.4.8. Inheritance, Overriding, and Hiding
https://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.4.8

A class C inherits from its direct superclass all concrete methods m (both static and instance) of the superclass for which all of the following are true:

  • m is a member of the direct superclass of C.

  • m is public, protected, or declared with package access in the same package as C.

  • No method declared in C has a signature that is a subsignature (§8.4.2) of the signature of m. ..... .....

    8.4.8.1. Overriding (by Instance Methods)

  • An instance method mC declared in or inherited by class C, overrides from C another method mA declared in class A, iff all of the following are true: .....
  • One of the following is true:
    • mA is public.
    • mA is protected.
    • mA is declared with package access in the same package as C, .....

The above means, that you can't override a private method, and a class B actually doesn't override fun.
If you either remove private modifier or declare fun as public or protected, then the code returns 5, because the fun method becomes "overrideable".

krokodilko
  • 32,441
  • 5
  • 40
  • 67