开发者

constructor java/C# taking in argument the mother class

开发者 https://www.devze.com 2023-02-19 09:31 出处:网络
I have a class that I have derivated to add some fields. class B: A{ private sthg ; public B(A a, String sthg){

I have a class that I have derivated to add some fields.

class B: A  {

private sthg ;

public B(A a, String sthg){
 //
}
}

I wonder what I have to do in the constructor in order to have a link between my A object passed to the contructor a开发者_开发问答nd my object.

Thank you.


whats' wrong with inheritance?

class B extends A {
    public B(...) {
        super();
        ...
    }
}

...well, if you really want to have an instance of B() such as it can handle an A() instance, you can add an A parameter to B

class B extends A {
    A a;
    ...
    public B(A a, ...) {
        super(); 
        this.a = a;
        ...
    }
}

but, in this case, I really don't see what's the need to B to extends A.

class B {
    A a;
    ...
    public B(A a, ...) {
        this.a = a;
        ...
    }
 }
0

精彩评论

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

关注公众号