2

I am preparing for an Oracle examination and answered incorrectly to the following question:

the combination abstract private is legal for inner classes

As it turns the answer is true, I answered false, as I could not find any use cases for having an abstract private inner class, that cannot be overridden from subclasses. Can someone explain, why/for what do we have that in the language?

almeynman
  • 7,088
  • 3
  • 23
  • 37

2 Answers2

3

The Java language specification defines the meaning of private members as follows:

Otherwise, the member or constructor is declared private, and access is permitted if and only if it occurs within the body of the top level class (§7.6) that encloses the declaration of the member or constructor.

That is, a private inner class is accessible (and may be subclassed) from any code residing in the same source file. For instance, you could do:

public class C {

   private abstract class A {
       abstract void foo();
   }

   void bar() {
       new A() {
           @Override void foo() {
               // do something
           }
       }
   }
}

It is interesting to note that a method declared private can not be overriden, but methods in private classes can be.

meriton
  • 68,356
  • 14
  • 108
  • 175
0

the combination abstract private is legal for inner classes

Its a bit confusing but the rule is that an inner class can't have an abstract private method.

if exam is saying the contrary then its wrong.

UPDATE: if what you mean is in class declaration, then answer is true, check this valid piece of code...

public class MyOuter {
    abstract private class MyInner {
        //the combination abstract private is legal for inner classes: TRUE
    }
}

To know why or when use it, check the suggested link, there is a good explanation about this...

Community
  • 1
  • 1
Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109