I have a problem with an extended class.
This are the classes:
class A{
}
class B extends A{
}
Now the problem is that I have a method that returns A , something like this:
public A doSomthing(){
}
And now I try to do something like this:
public static void main(){
B b = new B();
b = doSomething();
}
But it doesn't seem to work. Is there any way to solve this problem?
The only thing I thought about is it to have something like this:
class B extends A{
public B(A a){
copy all the fields from A to B}
}
And then do:
A a = new A();
a = doSomthing();
B b = new B(a);
Is there a better option?
Fundamentally I think you've missed what the assignment operator does. This statement:
b = doSomething();
changes the value of b
to whatever the doSomething()
method returns. It doesn't depend on the existing value of b
at all. So similarly, when you have:
A a = new A();
a = doSomthing();
... it would make more sense to write:
A a = doSomething();
Now if you need to create an instance of B
based on an instance of A
, then it may well make sense to write:
A a = doSomething();
B b = new B(a);
or just:
B b = new B(doSomething());
... but you need to understand when existing values are used and when they're not.
Usually I find that when I need to do something like that, it's actually better to use composition than inheritance anyway - that B
should have a reference to an existing A
rather than extending A
. That's certainly something to consider, but without a concrete example we can't say for sure.
See more on this question at Stackoverflow