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();
    }
} 
Share:
28,575
user1042304
Author by

user1042304

Updated on March 05, 2020

Comments

  • user1042304
    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
    user1042304 about 12 years
    I 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
    user1042304 about 12 years
    You have it the other way around..I want the Main Class to call a function that was written in the Other Class.
  • Louis Wasserman
    Louis Wasserman about 12 years
    Could you provide the complete source? You should probably just be calling Function() in the main class, rather than Other.Function(), since Main has the Function method itself -- it's just being implemented by Other.
  • Abdullah Jibaly
    Abdullah Jibaly about 12 years
    Updated according to your comments.
  • Hovercraft Full Of Eels
    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
    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
    user1042304 about 12 years
    I liked your second option, however Function() is not being altered by the extended class.
  • Old Pro
    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
    user1042304 about 12 years
    I 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
    Old Pro about 12 years
    @user1042304 I added an example for you.