Click to See Complete Forum and Search --> : Call a method from the parent class?
Znupi
11-26-2007, 09:18 AM
Is there a way to call from an instantiated class a method of the instantiating class? Here's what I mean, let's say I have two files:
MainClass.java
public class MainClass {
public static void testFunc() {
System.out.println("testFunc() was called!");
}
public static void main(String[] args) {
SubClass mySubClass = new SubClass();
}
}
SubClass.java
public class SubClass {
public static void SubClass() {
PARENT_CLASS.testFunc();
}
}
Is there a way to do this? I am very new to Java so please bear with me and tell me if I'm dead wrong :o
chazzy
11-26-2007, 08:55 PM
well, that depends
Does SubClass extend MainClass? if so then you can call it using the super keyword.
If it doesn't, then you need to create an instance of MainClass to invoke it.
Znupi
11-27-2007, 10:50 AM
No, it doesn't extend it. But here's another method I think wold work (didn't test it yet):
MainClass.java
public class MainClass {
public static void testFunc() {
System.out.println("testFunc() was called!");
}
public static void main(String[] args) {
SubClass mySubClass = new SubClass(this);
}
}
SubClass.java
public class SubClass {
public static void SubClass(MainClass parentClass) {
parentClass.testFunc();
}
}
Eventually I can store parentClass in an instance variable. Is this a good way of doing it? Are there better ways?
Thanks :)
chazzy
11-27-2007, 07:07 PM
just so you know, when you talk about a "parent class" and "subclass" it's typically expected that the parent class means that it's the base class for the subclass. :)
there's several forms of polymorphism - there's polymorphism by inclusion/containment and polymorphism by extension. both work. containment is better at encapsulating changes, but extending is standard.
As for your example, you can't use "this" keyword in a static method. static methods have no instance relationship.
Znupi
11-28-2007, 12:08 PM
That makes sense. Actually, in my application I wasn't using it in a static method, I was using this in a class constructor, like:
BaseClass.java
import javax.swing.*;
public class BaseClass extends JApplet {
public BaseClass() {
SubClass subclass = new SubClass(this);
}
}
I guess this way it should work, right?
Thanks for your replies :)