开发者

Java inheritance appending a function instead of overwriting it

public class C开发者_StackOverflowls1{
    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?


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.


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

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

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


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


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜