The Artima Developer Community
Sponsored Link

Legacy Java Answers Forum
September 2000

Advertisement

Advertisement

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:

Yes, you can do it...

Posted by Kishori Sharan on September 23, 2000 at 12:51 PM

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:

Sponsored Links



Google
  Web Artima.com   
Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us