Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Not to Inherit

 
shruti patel
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Is any to make class not to inherit other than using Final keyword
 
Steve Luke
Bartender
Posts: 4181
22
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could make all the constructors private (then you would have to use static factory methods to get instances).
 
Campbell Ritchie
Sheriff
Pie
Posts: 49733
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But if you only have a private constructor you ought to mark the class "final" to prevent anybody trying to extend it.
 
Bill Shirley
Ranch Hand
Posts: 457
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
it took me a while to understand the question, so I rewrote it...

paraphrased from shruti patel:
Hi,
Is there any way to make a class not allow another class to inherit from it, other than using the final keyword?
 
Ankit Garg
Sheriff
Posts: 9527
32
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
if you make all the constructors private, then no one can create instances of that class. so then you will also have to provide a factory method

 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Ankit Garg:
if you make all the constructors private, then no one can create instances of that class. so then you will also have to provide a factory method




You need to make your factory method static and it should also return an instance of Final.

[ August 20, 2008: Message edited by: Joanne Neal ]
[ August 20, 2008: Message edited by: Joanne Neal ]
 
Ankit Garg
Sheriff
Posts: 9527
32
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ya thanks...I forgot that....
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic