• Post Reply Bookmark Topic Watch Topic
  • New Topic

how can i prevent subclasses from adding new methods?  RSS feed

 
hani se
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi friends,
how can i prevent subclasses from adding new methods?
thanks.
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16057
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can't.

The only thing you can do is prevent a subclass from overriding a method, by making that method final in the superclass.

But there's no way to prevent subclasses from adding arbitrary methods. Why do you think you need this? If you explain it in more detail, we can help you with the actual problem you're trying to solve.
 
hani se
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jesper de Jong wrote:You can't.

The only thing you can do is prevent a subclass from overriding a method, by making that method final in the superclass.

But there's no way to prevent subclasses from adding arbitrary methods. Why do you think you need this? If you explain it in more detail, we can help you with the actual problem you're trying to solve.


this is my problem:
I have one class that i want to have one instance only, this is my code:


but it is possible to subclass it and define a new public constructor to instantiate another Singleton, Furthermore, the subclass can declare a new 'public instance' method to instantiate many singleton objects. how can i have only one instance of singleton that any subclass can't be able to instantiate another?
 
Roel De Nijs
Sheriff
Posts: 11338
177
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Likes 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
emma smith wrote:but it is possible to subclass it and define a new public constructor to instantiate another Singleton

That's not true! In this code snippet, class Def fails to compile because the constructor of class Abc is not visible (because it's private).

emma smith wrote:how can i have only one instance of singleton that any subclass can't be able to instantiate another?

If you don't want subclasses to be created, just make the Singleton class finalSince Java 5.0 you could use an enum to represent the singleton design pattern as wellAnd you don't have to worry about subclassing, because that's not allowed with an enum.

Hope it helps!
Kind regards,
Roel
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!