File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Final Class cannot be instantiated Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Final Class cannot be instantiated" Watch "Final Class cannot be instantiated" New topic
Author

Final Class cannot be instantiated

Alpesh Rathod
Ranch Hand

Joined: Jan 06, 2009
Posts: 41
class A{}
class B extends A{}
class C extends A{}

final class D extends B{
public void doMethod(){
A a=new B();
B b=new D();
C c=new C();
D d=null;
//Insert Here
}
}


d=(D)(B)a; //gives class cast exception.

Now in the above code how come an instance of D can be made since D is a final class...as far as i know that final class is never instantiated.

I m confused ...Help me..


Thanks,
Alps
James Tharakan
Ranch Hand

Joined: Aug 29, 2008
Posts: 580

final keyword tell that it cnnot be extended by any other class.

Ex:-
class E extends C{} ///ERROR


SCJP 6
Why to worry about things in which we dont have control, Why to worry about things in which we have control ! !
sunil langeh
Ranch Hand

Joined: Sep 04, 2007
Posts: 88
Dear Rathod, A final class can not be sub classed but it doesn't mean it can not be instantiated......


Thanks
Sunil (SCJP 5)
Alpesh Rathod
Ranch Hand

Joined: Jan 06, 2009
Posts: 41
Yeah i went wrong......my mistake....thanks
Djonatah Stiegler
Ranch Hand

Joined: Oct 30, 2008
Posts: 32
[Bad Post]Sorry[/Bad Post]



From Brazil
Djonatah Stiegler
Ranch Hand

Joined: Oct 30, 2008
Posts: 32
sunil langeh wrote:Dear Rathod, A final class can not be sub classed but it doesn't mean it can not be instantiated......



Ok, but why is this a compile time error?

thanks
<><
Punit Singh
Ranch Hand

Joined: Oct 16, 2008
Posts: 952
This is not a compile time error, this is runtime ClassCastException.


SCJP 6
Djonatah Stiegler
Ranch Hand

Joined: Oct 30, 2008
Posts: 32
Yes Punit,

I saw it few seconds before your post...I was stupid..

thanks.
<><

 
wood burning stoves
 
subject: Final Class cannot be instantiated