Calling function of an extended class
28,575
public class BaseCls {
void function() {
System.out.println("Base");
}
}
public class ExtCls extends BaseCls {
void function() {
super.function();
System.out.println("ExtCls");
}
public static void main(String args[]) {
new ExtCls().function();
}
}
Author by
user1042304
Updated on March 05, 2020Comments
-
user1042304 about 4 years
I would like to call a function of an extended class. How can this be done?
class Main{ Function(); } class Other extends Main{ public void Function() { /* The function code */ } }
-
user1042304 about 12 yearsI used an instance of: Other instance = new Other(); And tried calling: Other.Function() back in the main class. It says that it is unable to find the function. I think I am misunderstanding how this works. I've done a lot of reading on it. Can you provide a little more feedback on how to accomplish this please?
-
user1042304 about 12 yearsYou have it the other way around..I want the Main Class to call a function that was written in the Other Class.
-
Louis Wasserman about 12 yearsCould you provide the complete source? You should probably just be calling
Function()
in the main class, rather thanOther.Function()
, since Main has theFunction
method itself -- it's just being implemented byOther
. -
Abdullah Jibaly about 12 yearsUpdated according to your comments.
-
Hovercraft Full Of Eels about 12 years@user1042304: no you should never to this. Please see my comment to your original question. To get better help, tell us the details including the overall problem you're trying to solve, not how you're trying to solve it.
-
Hovercraft Full Of Eels about 12 years@AbdullahJibaly: I was commenting on user's comment above, not on your answer. He stated that he want's a parent class to call a child's method. Now if he meant a Parent variable to call a child's variable, then that's fine.
-
user1042304 about 12 yearsI liked your second option, however Function() is not being altered by the extended class.
-
Old Pro about 12 years@user1042304, you cannot have it both ways. Either you want to call a function that is defined in the extended class or you do not. If the extended class is not altering the function, then in what sense is it "a function of an extended class"?
-
user1042304 about 12 yearsI do want to call the function created in the extended class. But your suggestion here is showing Function() as empty defined in the Main class, and then again defined in the Extended Class.
-
Old Pro about 12 years@user1042304 I added an example for you.