Call subclass method in superclass but not the other classes
Jack Lau
Ranch Hand
Joined: Aug 30, 2002
Posts: 166
posted
0
Hello,
If there is a private method in subclass and I want to call it in the superclass, however, I want the subclass method only called by superclass. I know I can add one public method in subclass and called by superclass but it also cause a security issue.....does anyone know how to do?
Thanks, Jack
Ulf Dittmer
Marshal
Joined: Mar 22, 2005
Posts: 35252
7
posted
0
Private methods can't be called from outside a class. But having a superclass know something about one of its subclasses (like that it has a particular method m, and when to call it) runs counter to the idea of an OO hierarchy. The subclass should be calling methods in the superclass, not the other way around.
Well, you can make the method in the subclass protected instead of private and abstract protected in the superclass (as you did in the example). Then your superclass can use the abstract method and the method is not exposed to the whole world (only the class hierarchy (what you want) and the package). This will work fine and is not against OO principles.
Adam Schaible
Ranch Hand
Joined: Oct 04, 2007
Posts: 101
posted
0
According to the OP, he doesn't want other sub-classes to be able to call this method. This leads me to believe your domain model needs a look, or your trying to iterate over instances of the superclass generically and call this method if they are of a certain type.
There are definately programatic ways of doing this, but you may take a look at the design side of it before going down that road - problems like these are indicative of a design problem.
Jack Lau
Ranch Hand
Joined: Aug 30, 2002
Posts: 166
posted
0
Actually I want to use a template pattern so that I can minimize the coding in sub class. The super class is a Sup_JInternalFrame and the sub class is Sub_JInternalFrame extends Sup_JInternalFrame..... I think that the "Create", "Show", "Query", "Save" methods in all the sub class are doing the simular stuff but some logic can be on super class so I create "Create", "Show", "Query", "Save" methods in super class. However, in the sub class, all that methods are called in button actionPerformed and all the methods are private. I think it is make sense to set the methods private because only that JInternalFrame call it..... so I don't know how to make the code both secure and flexible.
Thanks, Jack
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.
subject: Call subclass method in superclass but not the other classes