tags:

views:

57

answers:

2

I was wondering about few of the below OOP concepts 1) abstract class cannot have final constructor. Why cant subclasses have same same constructor without rewriting them 2) abstract method cannot be private . We can still implement the abstract class in same file. So why not allow this

A: 

If a class has a final constructor, it isn't abstract.

If a class has a private method, no derived class could override it, thus the base class isn't abstract.

Perhaps you'd like

  • a non-abstract final base class with an abstract interface
  • a protected method in the base class which allows derived classes to override it

instead.

msw
@mswnon-abstract final base class!! didn get you
Ravisha
A: 

In Java, no constructor can be final. Constructors are not inherited at all.

Private methods are not inherited, so a private abstract method could not be implemented. Compare this to C++, in which private methods may oddly be overridden by derived classes.

From the Java Language Specification

8.8.3 Constructor Modifiers Unlike methods, a constructor cannot be abstract, static, final, native, strictfp, or synchronized. A constructor is not inherited, so there is no need to declare it final and an abstract constructor could never be implemented.

8.4.3.1 abstract Methods ... It is a compile-time error for a private method to be declared abstract. It would be impossible for a subclass to implement a private abstract method, because private methods are not inherited by subclasses; therefore such a method could never be used.

Andy Thomas-Cramer
Wont inner classes have access to private methods???
Ravisha
Yes. Inner classes can call private methods of their enclosing class. However, private methods are never inherited by subclasses, regardless whether they're abstract or not, and regardless whether the subclasses are inner or not. You could restrict access to abstract methods by declaring them in a private interface.
Andy Thomas-Cramer