I'm new to Java, maybe this is a silly question.
Let's say I have a src.utils
package containing the following classes:
public class ClassC {
public String sC = "I'm C";
}
public class ClassB extends ClassC {
}
public class ClassA {
public ClassB cB;
public String sA;
public void setCB(ClassB cB) {
this.cB = cB;
this.sA = cB.sC;
}
}
And a src
package containing the following classes:
import src.utils.*;
public class NewClassB extends ClassB {
public String sC = "I'm NewB";
}
public class Application {
public static void main(String[] args) {
NewClassB ncB = new NewClassB();
ClassA cA = new ClassA();
cA.setCB(ncB); // Here I'm passing an object of type NewClassB instead of ClassB
System.out.println(cA.sA); // Here I get "I'm C" instead of "I'm new B"
}
}
Important: I don't want to mention or write the NewClassB
anywhere in the src.utils
package. It's just a class that I developed later.
The problem is:
Why am I getting "I'm C" when running the main
class? I am passing to ClassA
an object of type NewClassB
(instead of ClassB
), and I have overwritten the sC
attribute in the definition of NewClassB
.
How could I do?
I tried with an interface, but then I couldn't instantiate it.