tags:

views:

94

answers:

6
public class Cls1{
    public foo(){
        doX();
    }
}

public class Cls2{
    public foo(){
        doY();
    }
}

Cls2 cls = new Cls2();
cls.foo();

Is there a way to do inheritance in java that java runs both doX and doY when the user calls the function with foo?

+3  A: 
public class Cls1 {
    public foo{
        doX();
    }
}

public class Cls2 extends Cls1 {
    public foo{
        super.foo();
        doY();
    }
}

Cls2 cls = new Cls2();
cls.foo();
pablochan
+5  A: 

Yes, but you have to do it explicitly:

public class Cls1{
    public foo{
        doX();
    }
}

public class Cls2 extends Cls1 {
    public foo{
        super.foo();
        doY();
    }
}

Note: I assume you meant for Cls2 to extend Cls1, otherwise your question makes no sense at all.

Jim Garrison
A: 

Assuming that Cls1 and Cls2 inherit from each other in some way, you can use the keyword super to call the superclass's implementation of a method if you want to, for instance, in the derived class perform both functions.

Donnie
+1  A: 
private class Cls2 extends Cls1 {      
    public void foo {
        doY();
        super.foo();
    }
}
Viele
+1  A: 

first of all, I assume you mean:

public class Cls2 extends Cls1{

and yes, there is:

public (something?) foo(){
    super.foo();
    doY();
}

The super keyword allows access to the super-class's methods. If it's simply called on its own:

super(...);

then it calls the super-class's constructor.

tlayton
A: 

If doX() and doY() were statically imported (which, as they were not defined in Cls1 or in Cls2 is the only way I can think of for this program to compile), then you can make a new class with a method foo that calls doX and doY without using inheritance. Those methods named foo would have nothing to do with each other, however.