This page contains an archived post to the Java Answers Forum made prior to February 25, 2002.
If you wish to participate in discussions, please visit the new
Artima Forums.
Message:
Clever solution
Posted by cannyq on September 27, 2000 at 2:41 PM
A lot more work than using final, but it is a clever solution and answers the question. > Hi MuraliKrishna > Yes, you can have a class which cannot be inherited without declaring it as a final class. Whenever, you extend a class the constructor of the derived class implicitly calls the default constructor of the ancestor class. If you declare a default construtor in your ancestor class as private then you cannot extend it because derived class has no access to its ancestor class default constructor.However, if you declare any other constructors in ancestor class then all have to be private. This creates another problem and you cannot create an object of your ancestor class because all constructors are private. So you will have to create a public static method for every constructor in your ancestor class which will return an object of that class. So when you need an object of your ancestor class you will call > that static method passing the desired parameters. > > Thanx > Kishori > > /////////// B.java > class A { > private A ( ) { > } > private A ( int i ) { > System.out.println ( " Created A with : " + i ) ; > } > public static A createA ( ) { > return new A ( ) ; > } > public static A createA ( int i ) { > return new A ( i ) ; > } > } > class B { // cannot wrire class B extends A > public static void main ( String[] args ) { > // Create an object of class A > A.createA ( 10 ) ; > } > }
Replies:
|